Python的scrapy爬蟲框架 Rule

2021-09-08 19:17:22 字數 1694 閱讀 3513

解釋:

rule是在定義抽取鏈結的規則,上面的兩條規則分別對應列表頁的各個分頁頁面和詳情頁,關鍵點在於通過restrict_xpath來限定只從頁面特定的部分來抽取接下來將要爬取的鏈結。

follow=false(不跟進), 只提取首頁符合規則的url,然後爬取這些url頁面資料,callback解析

follow=true(跟進鏈結), 在次級url頁面中繼續尋找符合規則的url,如此迴圈,直到把全站爬取完畢

rule(linkextractor(allow=(r''),), follow=true),

rule(linkextractor(allow=(r'\d+/index.html'),deny=(r'')),callback='parse_item', follow=true),

簡要說明

crawlspider是爬取那些具有一定規則**的常用的爬蟲,它基於spider並有一些獨特屬性

allow:這裡用的是re過濾,我們其實就是start_urls加上我們這個匹配到的具體鏈結下的內容。

linkextractor:故名思議就是鏈結的篩選器,首先篩選出來我們需要爬取的鏈結。

deny:這個引數跟上面的引數剛好想反,定義我們不想爬取的鏈結。

follow:預設是false,爬取和start_url符合的url。如果是true的話,就是爬取頁面內容所有的以start_urls開頭的url。

restrict_xpaths:使用xpath表示式,和allow共同作用過濾鏈結。還有乙個類似的restrict_css

callback:定義我們拿到可以爬取到的url後,要執行的方法,並傳入每個鏈結的response內容(也就是網頁內容)

注意:rule無論有無callback,都由同乙個_parse_response函式處理,只不過他會判斷是否有follow和callback』』』

# -*- coding: utf-8 -*-

import scrapy

from scrapy.spiders.crawl import rule,crawlspider

from scrapy.linkextractors import linkextractor

class ssspider(crawlspider):

name = 'ss'

# allowed_domains = ['toscrape.com']

start_urls = ['']

# 必須是列表

rules = [

#兩個rule可以二次提取url

rule(linkextractor(allow=(r''),), follow=true),

rule(linkextractor(allow=(r'\d+/index.html'),deny=(r'')),callback='parse_item', follow=true),

]def parse_item(self, response):

print(response.url)

name = response.xpath("//div[@id='a_main']/div[@class='bdsub']/dl/dd[1]/h1/text()").extract()

print(name)

Python爬蟲 scrapy框架

開源的,對平台的爬蟲框架 舊版本 需要預先定義所需欄位 class myitem scrapy.item url scrapy.field 再將所需欄位填充 class myspier scrapy.spider defparse self,response return sudo apt inst...

python爬蟲scrapy框架

安裝 pip install scrapy startproject 建立乙個新專案 genspider 根據模板生成乙個新爬蟲 crawl 執行爬蟲 shell 啟動互動式抓取控制台 進入專案目錄 scrapy startproject crawlertest project name cd cr...

Python爬蟲 Scrapy基礎

依照順序安裝如下依賴庫,如下 wheel pip install wheel lxml pyopenssl twisted pywin32 220 scrapy pip install scrapy 安裝成功後,通過在cmd的指定路徑下輸入 scrapy startproject hello可以在當...