python爬蟲爬取幽默笑話網(wǎng)站
爬取網(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í)間更少,更效率。
- 創(chuàng)建線程 池threadpool.ThreadPool()
- 創(chuàng)建需要線程池處理的任務(wù)即threadpool.makeRequests(),makeRequests存放的是要開啟多線程的函數(shù),以及函數(shù)相關(guān)參數(shù)和回調(diào)函數(shù),其中回調(diào)函數(shù)可以不寫(默認(rèn)是無)。
- 將創(chuàng)建的多個(gè)任務(wù)put到線程池中,threadpool.putRequest()
- 等到所有任務(wù)處理完畢theadpool.pool()
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è)文件,下載完成。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Python爬蟲之爬取最新更新的小說網(wǎng)站
- Python爬蟲設(shè)置Cookie解決網(wǎng)站攔截并爬取螞蟻短租的問題
- python爬蟲爬取某網(wǎng)站視頻的示例代碼
- python爬蟲實(shí)現(xiàn)爬取同一個(gè)網(wǎng)站的多頁數(shù)據(jù)的實(shí)例講解
- Python爬蟲自動(dòng)化獲取華圖和粉筆網(wǎng)站的錯(cuò)題(推薦)
- python爬蟲使用正則爬取網(wǎng)站的實(shí)現(xiàn)
- 詳解python 破解網(wǎng)站反爬蟲的兩種簡(jiǎn)單方法
- python爬蟲爬取筆趣網(wǎng)小說網(wǎng)站過程圖解
- 如何使用python爬蟲爬取要登陸的網(wǎng)站
- python 爬取吉首大學(xué)網(wǎng)站成績(jī)單
相關(guān)文章
Python中*args和**kwargs的區(qū)別詳解
這篇文章主要介紹了Python中*args和**kwargs的區(qū)別詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-09-09使用python和opencv的mask實(shí)現(xiàn)摳圖疊加
這篇文章主要介紹了使用python和opencv的mask實(shí)現(xiàn)摳圖疊加操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2021-04-04Python使用urlretrieve實(shí)現(xiàn)直接遠(yuǎn)程下載圖片的示例代碼
這篇文章主要介紹了Python使用urlretrieve實(shí)現(xiàn)直接遠(yuǎn)程下載圖片的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-08-08在Django的form中使用CSS進(jìn)行設(shè)計(jì)的方法
這篇文章主要介紹了在Django的form中使用CSS進(jìn)行設(shè)計(jì)的方法,Django是Python重多人氣開發(fā)框架中最為著名的一個(gè),需要的朋友可以參考下2015-07-07python實(shí)現(xiàn)字符串連接的三種方法及其效率、適用場(chǎng)景詳解
本篇文章主要介紹了python實(shí)現(xiàn)字符串連接的三種方法及其效率、適用場(chǎng)景詳解,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下。2017-01-01