Python Scrapy:返回被抓取的URL列表



我正在使用scratchy从单个域中刮取所有链接。我正在关注域上的所有链接,但保存域外的所有链接。下面的scraper工作正常,但我无法从scraper中访问成员变量,因为我使用CrawlerProcess运行它。

import scrapy
from scrapy.crawler import CrawlerProcess
class MySpider(scrapy.Spider):
name = 'myspider'
start_urls = ['https://example.com']
on_domain_urls = set()
off_domain_urls = set()
def parse(self, response):
links = response.xpath('//a/@href')
for link in links:
url = link.get()
if 'example.com' in url and url not in self.on_domain_urls:
print('On domain links found: {}'.format(
len(self.on_domain_urls)))
self.on_domain_urls.add(url)
yield scrapy.Request(url, callback=self.parse)
elif url not in self.off_domain_urls:
print('Offf domain links found: {}'.format(
len(self.on_domain_urls)))
self.off_domain_urls.add(url)
process = CrawlerProcess()
process.crawl(GoodOnYouSpider)
process.start()
# Need access to off_domain_links

如何访问off_domain_links?我可能会把它转移到全球范围,但这似乎是黑客行为。我也可以附加到文件,但如果可能的话,我希望避免文件I/O。有没有更好的方法来返回这样的聚合数据?

您检查Itempipeline了吗?我认为您必须在这种情况下使用它,并决定需要对变量执行什么操作。

请参阅:https://docs.scrapy.org/en/latest/topics/item-pipeline.html

最新更新