【问题标题】:Scrapy crawler gives out KeyErrorScrapy爬虫给出KeyError
【发布时间】:2019-12-27 16:43:09
【问题描述】:

我正在尝试使用 Scrapy 从英国网站抓取药物信息,但我收到“KeyError: 'Item does not support field: title'”。我无法弄清楚这里有什么问题。

我尝试使用 parse_item 函数使用 scrapy.Spider 类进行抓取。 x-paths 似乎工作正常。我一定对 Rule / LinkExtractor 对象有一些问题?

import scrapy
from scrapy.linkextractors import LinkExtractor 
from scrapy.spiders import CrawlSpider, Rule


class EMCSpider(CrawlSpider):
    name = 'emccrawler'
    allowed_domains = ['medicines.org.uk']
    start_urls = ['https://www.medicines.org.uk/emc/browse-medicines/']



     rules = (
    Rule(LinkExtractor(restrict_xpaths="//ul[@class='browse']/li/a"), 
        callback= 'parse_item', follow=True),
Rule(LinkExtractor(restrict_xpaths="//a[@class='search-paging- 
        next']"), callback= 'parse_item', follow=True),
Rule(LinkExtractor(restrict_xpaths="//div[@class='col-sm-9']/h2/a"), callback= 'parse_item', follow=True),
        )

    def parse_item(self, response):
        yield {
            'title': response.xpath("//div[@class='col-md-12 title']/h1/text()").get(),
            'company': response.xpath("//h2[@class='product']/a/text()").get(),
            'ingredient': response.xpath("//div[@class='col-xs-12 col-sm-6']/ul/li/text()").get(),
            'prescription': response.xpath("//div[@class='col-xs-12 col-sm-6']/p/text()").get(),
        }

--

【问题讨论】:

  • 你能发布完整的错误/回溯吗?
  • 您的代码似乎对我有用,所以我怀疑发生了一些奇怪的事情。你是怎么跑蜘蛛的?如果您在带有scrapy runspider emc_crawler.py 的新目录(而不是项目)中运行,它会工作吗?
  • @tomjn:这是完整的错误信息:pasteboard.co/ItX8oCa.png 另外,我在使用 scrapy runspider 时收到了同样的错误信息
  • 抱歉,图片中的最后一行被跳过了。这是新的:pasteboard.co/ItYtnKh.png
  • (如果您编辑帖子以包含回溯会更好)。但是看起来您发布的内容与上面的代码不对应?在底部你有... emc_crawler.py", line 19 in parse_item"。在我看来,第 19 行并不在 parse_item 中。此外,它说该行是item["title"] = response.xpath...,这与您上面的内容不匹配。你确定上面的代码是你正在运行的吗?

标签: python scrapy web-crawler


【解决方案1】:

对不起,伙计们,但我的项目设置似乎存在一些问题。只是创建一个新项目并复制爬虫对我有用。 感谢@tomjn 和大家帮助我解决问题。

【讨论】:

    猜你喜欢
    • 2019-06-24
    • 1970-01-01
    • 1970-01-01
    • 2021-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多