禁用scrapy内的递归抓取



几个月来,我一直在使用scrapy来验证我网站上的链接,它可以很好地爬行我的整个网站。现在我正在尝试更新我的脚本以禁用递归,我只想抓取一组特定的url,到目前为止我还没有成功。

sitesrap .py的内容

import scrapy
from scrapy.http import HtmlResponse
from scrapy.linkextractors import LinkExtractor
from scrapy.selector import Selector
from scrapy.spiders import CrawlSpider, Rule
from my_scrape.items import MyScrapeItem
class MySpider(CrawlSpider):
name = 'siteScrape'
allowed_domains = ['www.example.com']
start_urls = ['https://www.example.com/page']
rules = (
Rule(LinkExtractor(canonicalize=True, unique=True), callback='parse_item', follow=False),
)
def parse_item(self, response):
for link in response.xpath("//a"):
yield {
'ANCHOR_TEXT': ','.join(link.xpath("text()").getall()),
'TARGET_URL': ','.join(link.xpath("@href").getall()),
}
下面是pipelines.py中的相关类
class CsvPipeline(object):
@classmethod
def from_crawler(cls, crawler):
return cls(crawler.settings)
def __init__(self, settings):
csvFile = settings['CSV_FILE']
self.file = open(csvFile, 'wb')
self.exporter = CsvItemExporter(self.file, str)
self.exporter.start_exporting()
def close_spider(self, spider):
self.exporter.finish_exporting()
self.file.close()
def process_item(self, item, spider):
self.exporter.export_item(item)
return item

我的问题是我的页面有15个链接,这是抓取每一个(但没有任何进一步)。如果我设置follow=True,它可以完美地递归抓取整个网站。

我尝试更新这个使用Spider而不是CrawlSpider,运行没有错误,但返回一个空的CSV文件。我如何更新我的递归刮板,只拉出明确列出的页面的内容?

经过一番研究,我终于破解了这个问题& &;错误。我了解到的是,scrapy默认情况下不会递归地跟踪链接,我的原始蜘蛛是专门为此设置的。Spider返回0结果的原因是我没有正确地设置它来返回任何东西。因此,通过一些实验,我能够通过这个。

问题在我的蜘蛛文件中。下面是的版本siteScrape.py

import scrapy
from scrapy.http import HtmlResponse
from scrapy.linkextractors import LinkExtractor
from scrapy.selector import Selector
from my_scrape.items import MyScrapeItem
class MySpider(scrapy.Spider):
name = 'siteScrape'
allowed_domains = ['www.example.com']
start_urls = ['https://www.example.com/page']
def parse(self, response):
for link in response.xpath("//a"):
yield {
'ANCHOR_TEXT': link.xpath("text()").get(),
'TARGET_URL': link.xpath("@href").get(),
}

这个爬行器抓取一个页面www.example.com/page,并返回锚文本&页面上每个链接的目标URL。我的管道根本没有改变,我可以毫无问题地将这些结果发送到CSV文件。

最新更新