Python Scrapy多頁數(shù)據(jù)爬取實(shí)現(xiàn)過程解析
1.先指定通用模板
url = ’https://www.qiushibaike.com/text/page/%d/’#通用的url模板pageNum = 1
2.對parse方法遞歸處理
parse第一次調(diào)用表示的是用來解析第一頁對應(yīng)頁面中的數(shù)據(jù)
對后面的頁碼的數(shù)據(jù)要進(jìn)行手動(dòng)發(fā)送
if self.pageNum <= 5: self.pageNum += 1 new_url = format(self.url%self.pageNum) #手動(dòng)請求(get)的發(fā)送 yield scrapy.Request(new_url,callback=self.parse)
完整示例
class QiubaiSpider(scrapy.Spider): name = ’qiubai’ # allowed_domains = [’www.xxx.com’] start_urls = [’https://www.qiushibaike.com/text/’] url = ’https://www.qiushibaike.com/text/page/%d/’#通用的url模板 pageNum = 1 #parse第一次調(diào)用表示的是用來解析第一頁對應(yīng)頁面中的段子內(nèi)容和作者 def parse(self, response): div_list = response.xpath(’//*[@id='content-left']/div’) all_data = [] for div in div_list: author = div.xpath(’./div[1]/a[2]/h2/text()’).extract_first() content = div.xpath(’./a[1]/div/span//text()’).extract() content = ’’.join(content) # 將解析的數(shù)據(jù)存儲到item對象 item = QiubaiproItem() item[’author’] = author item[’content’] = content # 將item提交給管道 yield item # item一定是提交給了優(yōu)先級最高的管道類 if self.pageNum <= 5: self.pageNum += 1 new_url = format(self.url%self.pageNum) #手動(dòng)請求(get)的發(fā)送 yield scrapy.Request(new_url,callback=self.parse)
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 使用Python和百度語音識別生成視頻字幕的實(shí)現(xiàn)2. Gitlab CI-CD自動(dòng)化部署SpringBoot項(xiàng)目的方法步驟3. ASP中解決“對象關(guān)閉時(shí),不允許操作。”的詭異問題……4. IDEA版最新MyBatis程序配置教程詳解5. python pymysql鏈接數(shù)據(jù)庫查詢結(jié)果轉(zhuǎn)為Dataframe實(shí)例6. ASP刪除img標(biāo)簽的style屬性只保留src的正則函數(shù)7. idea設(shè)置自動(dòng)導(dǎo)入依賴的方法步驟8. 淺談SpringMVC jsp前臺獲取參數(shù)的方式 EL表達(dá)式9. 教你如何寫出可維護(hù)的JS代碼10. 詳解Java內(nèi)部類——匿名內(nèi)部類
