【问题标题】:Scrapy does not crawl through data contained in start URLsScrapy 不会爬取起始 URL 中包含的数据
【发布时间】:2014-10-30 23:45:09
【问题描述】:

我正在尝试使用 scrapy 抓取整个网站。根据 Scarpy 的文档

start_urls - 蜘蛛将开始抓取的 URL 列表, 当没有指定特定的 URL 时。所以,下载的第一页 将是这里列出的那些。后续会生成 URL 依次从起始 URL 中包含的数据开始。

所以根据这个定义,scrapy 应该通过start_urls 下提到的页面上的所有子 url,但它只抓取我指定的 url。我确实指定了Scrapy - Crawl whole website 中提到的规则,但它没有帮助。它只抓取和输出我在 start_urls 中指定的页面。

这是我的代码的 sn-p:

class AcdivocaFirstSpider(scrapy.Spider):
    name = "example_sample"
    allowed_domains = ["example.org"]
    start_urls = ["http://www.example.org/site/id/home"]
    rules = rules = [Rule(SgmlLinkExtractor(), callback='parse_item', follow=True)]

    def parse(self, response):
        filename = response.url.split("/")[-1] #so eg it would name 'home'
        open(filename, 'wb').write(response.body)

这会生成一个包含“主页”页面提取的 HTML 数据的单个文件。如何让它从首页开始递归爬取整个网站?

感谢任何帮助。谢谢你。

【问题讨论】:

    标签: python scrapy web-crawler


    【解决方案1】:

    要改变的两件事:

    • 要使用规则,使AcdivocaFirstSpider 成为scrapy.contrib.spiders.CrawlSpider 的子类,而不是scrapy.Spider

    后续的 URL 将从起始 URL 中包含的数据依次生成。

    这句话具有误导性。 scrapy.Spider 本身并没有对这些起始 URL 做任何特别的事情:它下载它们并将响应的正文传递给 parse()。如果实现parse() 回调以产生更多请求,那么是的,将从这些 URL 中的数据生成后续 URL,但这不是自动/自动的。

    • 使用scrapy.contrib.spiders.CrawlSpider 时,您需要NOT 覆盖内置的parse() 方法,这是检查规则并生成页面请求的地方。因此,您需要将 parse 重命名为 parse_item(在您的规则中引用)

    the warning in the docs on crawling rules.

    【讨论】:

    • 这有帮助!非常感谢,我最终没有覆盖默认的解析方法,而是定义了一个作为要使用的回调!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-07
    • 2021-11-20
    • 2013-01-24
    • 2015-10-18
    • 1970-01-01
    • 2017-09-22
    • 1970-01-01
    相关资源
    最近更新 更多