[Python] Scrapy
- 2023.03.15
- [Python] Scrapy
安裝
pip install scrapy
註1:pip 中 pyopenssl 版本為 22.1.0, cryptography 版本為 38.0.4
註2:scrappy scrapy
爬蟲
創建新專案
$ scrapy startproject {Project Name}
專案結構
- {Project Name}
- scrapy.cfg
- {Project Name}
- spiders
- __init__.py
- __init__.py
- items.py
- middlewares.py
- pipelines.py
- settings.py
- spiders
生成 Spider
在(最上層的){Project Name}
:
scrapy genspider {Spider Name} {Target URL}
會在{Project Name}/{Project Name}/spiders/
產生{Spider Name}.py
執行 Spider
在(最上層的){Project Name}
:
scrapy crawl {Spider Name}
Parse
修改 Spider 中的 parse(response)
Selector with XPath 
node = response.xpath('...')
然後用node.get()
取得內容
Join Absolute URL
response.urljoin(…)
Crawl Another Page Got from Result
yield scrapy.Request({URL}[, callback={Another Parsing Function}])
Item Pipeline
設定 settings.py
啟用 ITEM_PIPELINES
1Scrapy Doc.: Settings – Item Pipelines
ITEM_PIPELINES = {
"scrapy_spiders.pipelines.ScrapySpidersPipeline": 300,
}
數字表示優先度 (0 ~ 1000),數字小表示優先度高
撰寫 pipelines.py2Scrapy Doc.: Item Pipeline
process_item(self, item, spider)
open_spider(self, spider)
當 spider 被啟動時會被呼叫
close_spider(self, spider)
當 spider 被關閉時會被呼叫
@classmethod
from_crawler(cls, crawler)
AJAX 對策
尋找並分析頁面的 AJAX 請求 (Request)
Chrome
- 點擊滑鼠右鍵 → 檢查 → Tabs 中 ( » : More tabs) 找到 Network
- 觸發 AJAX 請求
→ 確認 Name 列表中的新增 XMLHttpRequest (XHR) 項目的傳回資料 (Preview 內容) - 分析 URL 中的請求參數 和傳回資料的格式
- URL:
Headers → General → Request URL - 傳回資料 (Preview 內容)
- URL:
送出 AJAX 請求並接受回應 (Response)
參考:requests
Useful Resources
Last Updated on 2025/04/13 by A1go