其實(shí)這兩天也正在接觸數(shù)據(jù)庫的內(nèi)容,可以將爬取下來的數(shù)據(jù)保存在數(shù)據(jù)庫中,以待以后的利用。好了,廢話不多說了,先來看看程序爬取的數(shù)據(jù)結(jié)果
值得一提的是,我在程序中想一下子爬取糗事百科 30 頁的內(nèi)容,但是出現(xiàn)了連接錯誤,當(dāng)我把頁數(shù)降到 20 頁的時候,程序就可以正常的跑起來了,不知道是什么原因,渴望知道的大神可以告訴我一聲,感激不盡。
程序非常簡單,直接上源代碼咯
# coding=utf8 import re import requests from lxml import etree from multiprocessing.dummy import Pool as ThreadPool import sys reload(sys) sys.setdefaultencoding('utf-8') def getnewpage(url, total): nowpage = int(re.search('(d+)', url, re.S).group(1)) urls = [] for i in range(nowpage, total + 1): link = re.sub('(d+)', '%s' % i, url, re.S) urls.append(link) return urls def spider(url): html = requests.get(url) selector = etree.HTML(html.text) author = selector.xpath('//*[@id="content-left"]/p/p[1]/a[2]/@title') content = selector.xpath('//*[@id="content-left"]/p/p[2]/text()') vote = selector.xpath('//*[@id="content-left"]/p/p[3]/span/i/text()') length = len(author) for i in range(0, length): f.writelines('作者 : ' + author[i] + ' ') f.writelines('內(nèi)容 :' + str(content[i]).replace(' ','') + ' ') f.writelines('支持 : ' + vote[i] + ' ') if __name__ == '__main__': f = open('info.txt', 'a') url = 'http://www.qiushibaike.com/text/page/1/' urls = getnewpage(url, 20) pool = ThreadPool(4) pool.map(spider,urls) f.close()
如果其中有不懂得部分,可以依次參考我的前三篇文章。
更多Python 制作糗事百科爬蟲相關(guān)文章請關(guān)注PHP中文網(wǎng)!
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com