Mike的Python學院

Terminal server、XPath、系統日誌分析、Scrapy、Python爬蟲、CSS、程式語言、網頁爬蟲、Python網路爬蟲、Python、Visual Studio、資料擷取

Mike Ku

Learn Code With Mike品牌創辦人

2021/12/29

學會使用3個Scrapy網頁爬蟲偵錯技巧提升開發效率

Q:Scrapy Shell(互動介面)是什麼?
Scrapy Shell是一個互動式的終端(Terminal)介面,讓開發人員可以不需要等到整個Scrapy專案完成就能夠進行測試,主要是用來測試Scrapy框架使用css()或xpath()方法(Method)爬取資料的結果。
舉例來說,用Visual Studio Code開啟Scrapy專案,在終端介面(Terminal)的地方,利用以下的指令開啟Scrapy Shell:
如果想要確認回應的結果,可以使用以下的Scrapy Shell指令:
>>>view(response)
True
除此之外,假設要爬取其中的新聞標題,就可以在Scrapy Shell的互動式介面中,透過指令的方式,使用css()或xpath()方法(Method)來測試是否能夠爬取成功,如下範例:
>>> response.css("h3.post_title a.js-auto_break_title::text").get()
'Appier 將於東京交易所掛牌,市值估突破 10 億美元'
Q:Scrapy Logging(日誌)如何使用?
Scrapy網頁爬蟲另一個最常用來偵錯的方法就是Logging(日誌),依據重要的程度分為五種日誌類型,由高到低為:critical、error、warning、info、debug,由於Scrapy框架的網頁爬蟲類別(spiders)本身就已經有logger物件,所以無需引用就可以在網頁爬蟲中使用,如下範例:
class HotNewsSpider(scrapy.Spider):
name = 'hot_news'
allowed_domains = ['www.inside.com.tw']
def parse(self, response):
# 熱門文章標題
hot_news_title = response.xpath(
"//h1[@class='title']/text()").get()
if hot_news_title:
return hot_news_title
else:
self.logger.error("沒有爬取到熱門文章標題")
接下來,開啟Scrapy專案的settings.py檔案,加入以下設定,如下範例:
LOG_FILE = "inside_log.txt"
LOG_LEVEL = "ERROR" #特別注意這邊一定要大寫
其中「LOG_LEVEL(日誌層級)」可以自訂在哪一個日誌類型以上需要被記錄到日誌檔中,預設為DEBUG。
而Scrapy網頁爬蟲(spiders)模組以外,如果想要使用Logging(日誌),就需要引用logging模組(Module),以ITEM PIPELINE資料模型管道(pipelines.py)為例,如下範例:
from itemadapter import ItemAdapter
from scrapy.exporters import CsvItemExporter
import logging
class CsvPipeline:
def __init__(self):
self.file = open('posts.csv', 'wb')
self.exporter = CsvItemExporter(self.file, encoding='big5')
self.exporter.start_exporting()
def process_item(self, item, spider):
if item:
self.exporter.export_item(item)
return item
else:
logging.error("無資料匯出!")
...
如果想要學習更多的Python應用教學,歡迎前往Learn Code With Mike(https://www.learncodewithmike.com/2021/03/scrapy-spiders-debug.html
)網站觀看更多精彩內容。
2 0 528 0