您好,登錄后才能下訂單哦!
爬取網(wǎng)站為:http://xiaohua.zol.com.cn/youmo/
查看網(wǎng)頁機(jī)構(gòu),爬取笑話內(nèi)容時(shí)存在如下問題:
1、每頁需要進(jìn)入“查看更多”鏈接下面網(wǎng)頁進(jìn)行進(jìn)一步爬取內(nèi)容每頁查看更多鏈接內(nèi)容比較多,多任務(wù)進(jìn)行,這里采用線程池的方式,可以有效地控制系統(tǒng)中并發(fā)線程的數(shù)量。避免當(dāng)系統(tǒng)中包含有大量的并發(fā)線程時(shí),導(dǎo)致系統(tǒng)性能下降,甚至導(dǎo)致 Python 解釋器崩潰,引入線程池,花費(fèi)時(shí)間更少,更效率。
2、查看鏈接笑話頁內(nèi)容,div元素內(nèi)部文本分布比較混亂。有的分布在<p>鏈接內(nèi)有的屬于div的文本,可采用正則表達(dá)式的方式解決。
注意2種獲取元素節(jié)點(diǎn)的方式:
1)lxml獲取節(jié)點(diǎn)字符串
res=requests.get(url,headers=headers) html = res.text lxml 獲取節(jié)點(diǎn)寫法 element=etree.HTML(html) divEle=element.xpath("http://div[@class='article-text']")[0] # 獲取div節(jié)點(diǎn) div= etree.tostring(divEle, encoding = 'utf-8' ).decode('utf-8') # 轉(zhuǎn)換為div字符串
2)正則表達(dá)式寫法1,過濾回車、制表符和p標(biāo)簽
# 第一種方式:replace content = re.findall('<div class="article-text">(.*?)</div>',html,re.S) content = content[0].replace('\r','').replace('\t','').replace('<p>','').replace('</p>','').strip()
3)正則表達(dá)式寫法2,過濾回車、制表符和p標(biāo)簽
# 第二種方式:sub for index in range(len(content)): content[index] = re.sub(r'(\r|\t|<p>|<\/p>)+','',content[index]).strip() list = ''.join(content) print(list)
3、完整代碼
index.py
import requests import threadpool import time import os,sys import re from lxml import etree from lxml.html import tostring class ScrapDemo(): next_page_url="" #下一頁的URL page_num=1 #當(dāng)前頁 detail_url_list=0 #詳情頁面URL地址list deepth=0 #設(shè)置抓取的深度 headers = { "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.84 Safari/537.36" } fileNum=0 def __init__(self,url): self.scrapyIndex(url) def threadIndex(self,urllist): #開啟線程池 if len(urllist) == 0: print("請(qǐng)輸入需要爬取的地址") return False ScrapDemo.detail_url_list=len(urllist) pool=threadpool.ThreadPool(len(urllist)) requests=threadpool.makeRequests(self.detailScray,urllist) for req in requests: pool.putRequest(req) time.sleep(0.5) pool.wait() def detailScray(self,url): # 獲取html結(jié)構(gòu) if not url == "": url='http://xiaohua.zol.com.cn/{}'.format(url) res=requests.get(url,headers=ScrapDemo.headers) html=res.text # element=etree.HTML(html) # divEle=element.xpath("http://div[@class='article-text']")[0] # Element div self.downloadText(html) def downloadText(self,ele): # 抓取數(shù)據(jù)并存為txt文件 clist = re.findall('<div class="article-text">(.*?)</div>',ele,re.S) for index in range(len(clist)): ''' 正則表達(dá)式:過濾掉回車、制表符和p標(biāo)簽 ''' clist[index]=re.sub(r'(\r|\t|<p>|<\/p>)+','',clist[index]) content="".join(clist) # print(content) basedir=os.path.dirname(__file__) filePath=os.path.join(basedir) filename="xiaohua{0}-{1}.txt".format(ScrapDemo.deepth,str(ScrapDemo.fileNum)) file=os.path.join(filePath,'file_txt',filename) try: f=open(file,"w") f.write(content) if ScrapDemo.fileNum == (ScrapDemo.detail_url_list - 1): print(ScrapDemo.next_page_url) print(ScrapDemo.deepth) if not ScrapDemo.next_page_url == "": self.scrapyIndex(ScrapDemo.next_page_url) except Exception as e: print("Error:%s" % str(e)) ScrapDemo.fileNum=ScrapDemo.fileNum+1 print(ScrapDemo.fileNum) def scrapyIndex(self,url): if not url == "": ScrapDemo.fileNum=0 ScrapDemo.deepth=ScrapDemo.deepth+1 print("開啟第{0}頁抓取".format(ScrapDemo.page_num)) res=requests.get(url,headers=ScrapDemo.headers) html=res.text element=etree.HTML(html) a_urllist=element.xpath("http://a[@class='all-read']/@href") # 當(dāng)前頁所有查看全文 next_page=element.xpath("http://a[@class='page-next']/@href") # 獲取下一頁的url ScrapDemo.next_page_url='http://xiaohua.zol.com.cn/{}'.format(next_page[0]) if not len(next_page) == 0 and ScrapDemo.next_page_url != url: ScrapDemo.page_num=ScrapDemo.page_num+1 self.threadIndex(a_urllist[:]) else: print('下載完成,當(dāng)前頁數(shù)為{}頁'.format(ScrapDemo.page_num)) sys.exit()
runscrapy.py
from app import ScrapDemo url="http://xiaohua.zol.com.cn/youmo/" ScrapDemo(url)
運(yùn)行如下:
總共1988個(gè)文件,下載完成。
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。