我不明白为什么我的爬虫只抓取
start_url
,而忽略提取与allow
参数匹配的任何URL。from scrapy.crawler import CrawlerProcess
from scrapy.exceptions import DropItem
from scrapy.settings import Settings
from scrapy.spiders import Rule, CrawlSpider
from scrapy.linkextractors import LinkExtractor
class MySpider(CrawlSpider):
name = "my_spider"
allowed_domains = ["website.com/"]
rules = [Rule(LinkExtractor(allow='/product_page/'), callback='parse', follow=True)]
start_urls = ["http://www.website.com/list_of_products.php"]
custom_settings = {
"ROBOTSTXT_OBEY": "True",
"COOKIES_ENABLED": "False",
"LOG_LEVEL": 'INFO'
}
def parse(self, response):
try:
item = {
# populate "item" with data
}
yield MyItem(**item)
except (DropItem, Exception) as e:
raise DropItem("WARNING: Product item dropped due to obligatory field not being present - %s" % response.url)
if __name__ == '__main__':
settings = Settings()
settings.set('ITEM_PIPELINES', {
'pipelines.csv_pipeline.CsvPipeline': 100
})
process = CrawlerProcess(settings)
process.crawl(MySpider)
process.start()
我不确定这个问题是否由于从__name__
中调用而发生。
parse
肯定有问题,如果没有被调用,那么可能还有其他问题。可能是allowed_domains
或LinkExtractor
出了问题。我现在没有时间测试,但你能否尝试从允许的域中删除斜杠?即将其设置为["website.com"]
而不是["website.com/"]
?应该有一种方法可以在不重新定义parse
的情况下使其工作。 - Ismael Padillarules = [Rule(LinkExtractor(allow='/list_of_products/'), callback='parse', follow=True)]
调用基础的parse
回调函数,这样它就可以递归遍历所有页面。在我的情况下,该页面只列出了一个项目,所以只做了一次,没有继续扩展遍历其他页面。非常感谢你 Ismael,因为你找到了我覆盖基础parse
函数的关键问题,现在我给你颁发奖励。 - Carlos