【问题标题】:Spider error URL processing蜘蛛错误 URL 处理
【发布时间】:2018-02-25 17:37:48
【问题描述】:

我在使用 scrapy 1.5.0、python 2.7.14 处理 URL 时遇到错误。

class GoodWillOutSpider(Spider):

name = "GoodWillOutSpider"
allowded_domains = ["thegoodwillout.com"]
start_urls = [GoodWillOutURL]

def __init__(self):
    logging.critical("GoodWillOut STARTED.")

def parse(self, response):
    products = Selector(response).xpath('//div[@id="elasticsearch-results-container"]/ul[@class="product-list clearfix"]')

    for product in products:
        item = GoodWillOutItem()
        item['name'] = product.xpath('//div[@class="name ng-binding"]').extract()[0]
        item['link'] = "www.thegoodwillout.com" + product.xpath('//@href').extract()[0]
        # item['image'] = "http:" + product.xpath("/div[@class='catalogue-product-cover']/a[@class='catalogue-product-cover-image']/img/@src").extract()[0]
        # item['size'] = '**NOT SUPPORTED YET**'
        yield item

    yield Request(GoodWillOutURL, callback=self.parse, dont_filter=True, priority=16)

这是我的班级 GoodWillOutSpider,这是我得到的错误:

[scrapy.core.scraper] ERROR: Spider error processing <GET https://www.thegoodwillout.com/footwear> (referer: None)

line 1085, in parse item['name'] = product.xpath('//div[@class="name ng-binding"]').extract()[0] IndexError: list index out of range

而且我想知道将来,如果不在这里再次询问每个站点的正确 xpath,我怎么能得到呢

【问题讨论】:

    标签: python python-2.7 scrapy scrapy-spider


    【解决方案1】:

    问题

    如果您的抓取工具无法访问您可以使用浏览器开发人员工具查看的数据,那么它看到的数据与您的浏览器不同。

    这可能意味着以下两种情况之一:

    • 您的抓取工具已被识别并提供不同的内容
    • 部分内容是动态生成的(通常通过javascript)

    通用解决方案

    解决这两个问题的最直接的方法是使用实​​际的浏览器。

    有许多可用的无头浏览器,您可以根据自己的需要选择最好的浏览器。
    对于 scrapy,scrapy-splash 可能是最简单的选择。

    更专业的解决方案

    有时,您可以找出导致这种不同行为的原因,然后更改您的代码。
    这通常是更有效的解决方案,但可能需要您做更多的工作。

    例如,如果您的爬虫被重定向,您可能只需要使用不同的用户代理字符串、传递一些额外的标头或减慢您的请求。

    如果内容是由 javascript 生成的,您也许可以查看页面源代码(response.text 或在浏览器中查看源代码),并弄清楚发生了什么。

    之后,有两种可能:

    • 以另一种方式提取数据(就像 gangabas 为您上一个问题所做的那样)
    • 在您的蜘蛛代码中复制 javascript 正在执行的操作(例如发出其他请求,如当前示例中所示)

    【讨论】:

    • 你能解释一下gangabass是如何提取数据的吗?这似乎是解决我的问题的最佳方法
    • 通过查看源代码,其中包含在答案中。
    【解决方案2】:

    IndexError: 列表索引超出范围

    你需要先检查列表提取后是否有任何值

    item['name'] = product.xpath('//div[@class="name ng-binding"]').extract()
    if item['name']:
        item['name'] = item['name'][0]
    

    【讨论】:

    • 我很确定 xpath 是错误的......已经有这样的问题,一个人在没有告诉我如何获取 xpath 的情况下解决了它
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-19
    • 1970-01-01
    • 2011-02-20
    相关资源
    最近更新 更多