我希望scrapy抓取一些啓動URL,然後按照規則在這些頁面中鏈接。我的蜘蛛是從CrawlSpider
繼承,並有start_urls
和'規則'設置。但它似乎並沒有使用我定義的解析函數來解析start_urls。以下是代碼:scrapy用於解析的解析方法start_urls
<!-- language: lang-python -->
class ZhihuSpider(CrawlSpider):
start_urls = ["https://www.zhihu.com/topic/19778317/organize/entire",
"https://www.zhihu.com/topic/19778287/organize/entire"]
rules = (Rule(LinkExtractor(allow= (r'topic/\d+/organize/entire')), \
process_request='request_tagInfoPage', callback = 'parse_tagPage'))
# this is the parse_tagPage() scrapy should use to scrape
def parse_tagPage():
print("start scraping!") # Explicitly print to show that scraping starts
# do_something
但是,控制檯顯示scrapy抓取的是start_urls,但沒有打印任何東西。所以我很確定parse_tagPage()函數沒有被調用。儘管scrapy顯示這些網址已被抓取[scrapy] DEBUG: Crawled (200) <GET https://www.zhihu.com/topic/19778317/organize/entire> (referer: http://www.zhihu.com)
有關爲什麼會發生這種情況的任何提示以及如何設置scrapy以使用parse_tagPage()?
您應該閱讀文檔,當您提到start_urls時,scrapy將使用start_request()方法訪問該URL,然後會查看它是否符合您提到的規則,如果符合規則,則會訪問parse_tagPage()方法否則什麼都不會做(當沒有規則匹配時,你可以定義默認回調方法) http://doc.scrapy.org/en/latest/topics/spiders.html?highlight=start%20request#scrapy.spiders.Spider .start_requests – MrPandav
你可以回答自己的問題,然後接受你的答案,而不是用答案編輯問題。 –
謝謝Burhan!不知道。 – Skywalker326