scrapy獲取汽車之家資料
阿新 • • 發佈:2021-11-13
1、建立scrapy專案
>scrapy startproject scrapy_carhome
2、找到對應介面
3、建立爬蟲檔案
> cdscrapy_carhome\scrapy_carhome\spiders
scrapy_carhome\scrapy_carhome\spiders> scrapy genspider car https://car.autohome.com.cn/price/brand-15.html
4、註釋robots協議
//div[@class="main-title"]/a/text()
//div[@class="main-lever"]//span/span/text()
car.py
import scrapy class CarSpider(scrapy.Spider): name = 'car' allowed_domains = ['https://car.autohome.com.cn/price/brand-15.html'] # 注意如果你的請求的介面是html為結尾的 那麼是不需要加/的 start_urls = ['https://car.autohome.com.cn/price/brand-15.html'] def parse(self, response): name_list = response.xpath('//div[@class="main-title"]/a/text()') price_list = response.xpath('//div[@class="main-lever"]//span/span/text()') # 遍歷列表 for i in range(len(name_list)): name = name_list[i].extract() price = price_list[i].extract() print(name,price)
執行爬蟲檔案
scrapy_carhome\scrapy_carhome\spiders>scrapy crawl car
scrapy架構組成 1)引擎 —>自動執行,無需關注,會自動組織所有的請求物件,分發給下載器 2)下載器 —>從引擎處獲取到請求物件後,請求資料 3)spiders —>Spider類定義瞭如何爬取某個(或某些)網站。包括了爬取的動作(例如:是否跟進連結)以及如何從網頁的內容中提取結構化資料(爬取item)。 換句話說,Spider就是您定義爬取的動作及分析某個網頁(或者是有些網頁)的地方。 4)排程器 —>有自己的排程規則,無需關注 5)管道(Item pipeline) —>最終處理資料的管道,會預留介面供我們處理資料當Item在Spider中被收集之後,它將會被傳遞到Item Pipeline,一些元件會按照一定的順序執行對Item的處理。每個item pipeline元件(有時稱之為“Item Pipeline”)是實現了簡單方法的Python類。他們接收到Item並通過它執行一些行為,同時也決定此Item是否繼續通過pipeline,或是被丟棄而不再進行處理。 以下是item pipeline的一些典型應用: 1. 清理HTML資料 2. 驗證爬取的資料(檢查item包含某些欄位) 3. 查重(並丟棄) 4. 將爬取結果儲存到資料庫中 scrapy工作原理