您好,登錄后才能下訂單哦!
這篇文章主要介紹“python如何爬取豆瓣各分類書單”,在日常操作中,相信很多人在python如何爬取豆瓣各分類書單問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”python如何爬取豆瓣各分類書單”的疑惑有所幫助!接下來,請跟著小編一起來學(xué)習(xí)吧!
代碼展示:
pachon2.5.py
# -- coding: utf-8 --
import urllib
import urllib2
import re
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
class book: #豆瓣書籍的類
def init(self, types, page):
self.baseUrl = 'http://www.douban.com/tag/'
self.types = types
self.filename = 'doubanbook.txt'
self.page = page
def getContents(self): #爬取源代碼
try:
#if self.page == 0:
url = self.baseUrl + self.types + '/book'
#else:
# url = self.baseUrl + self.types + '/book?start=' + str(self.page)
user_agent = 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.65 Safari/537.36'
headers = { 'User-Agent' : user_agent}
request = urllib2.Request(url,headers = headers)
response = urllib2.urlopen(request)
content = response.read() #.decode('utf-8')
pattern = re.compile('<a href=.*?class="title".*?target="_blank">(.*?)</a>.*?>(.*?)</div>',re.S)
items = re.findall(pattern,content)
return items
except urllib2.URLError, e:
if hasattr(e, "reason"):
print u"豆瓣鏈接錯誤,錯誤原因", e.reason
return None
def writetext(self, items): #寫入txt
for item in items:
print item[0],item[1]
files = open(self.filename,'a')
files.write(item[0])
files.write(item[1])
files.write('\n')
files.close()
def strat(self): #啟動函數(shù)
self.writetext(self.getContents())
print u"""出現(xiàn)亂碼為正常現(xiàn)象,在與本腳本相同的文件夾下會多出一個,
doubanbook.txt的文件里面有所爬書籍,如你把本腳本放在桌面,
文件便會出現(xiàn)在桌面"""
print u"結(jié)束輸入 'O' , 聯(lián)系作者輸入 'A'"
end = raw_input('>')
if end == 'A':
print u"QQ郵箱:1021644861@qq.com"
raw_input('>')
else:
print "over"
到此,關(guān)于“python如何爬取豆瓣各分類書單”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識,請繼續(xù)關(guān)注億速云網(wǎng)站,小編會繼續(xù)努力為大家?guī)砀鄬嵱玫奈恼拢?/p>
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。