【问题标题】:Empty list with scrapy and Xpath带有scrapy和Xpath的空列表
【发布时间】:2015-11-03 21:39:27
【问题描述】:

我开始使用 scrapy 和 xpath 来抓取一些页面,我只是在使用 ipython 尝试简单的事情,我在 IMDB 等某些页面中得到响应,但是当我尝试在 www.bbb.org 等其他页面时我总是得到一个空列表。这就是我正在做的:

scrapy shell 'http://www.bbb.org/central-western-massachusetts/business-reviews/auto-repair-and-service/toms-automotive-in-fitchburg-ma-211787'

BBB 认证

自 2010 年 2 月 12 日起获得 BBB 认证的企业

BBB 已确定 Tom's Automotive 符合 BBB 认证标准,其中包括承诺……”

这一段的xpath是:

'//*[@id="business-accreditation-content"]/p[2]'

所以我使用:

data = response.xpath('//*[@id="business-accreditation-content"]/p[2]').extract()

但是data 是一个空列表,我正在使用 chrome 获取 Xpath,它可以在其他页面中使用,但是无论我尝试页面的哪个部分,我都什么也得不到。

【问题讨论】:

    标签: python xpath web-scraping scrapy


    【解决方案1】:

    网站实际上会检查 User-Agent 标头。

    如果你不指定它,看看它返回什么:

    $ scrapy shell 'http://www.bbb.org/central-western-massachusetts/business-reviews/auto-repair-and-service/toms-automotive-in-fitchburg-ma-211787'
    In [1]: print(response.body)
    Out[1]: 123
    
    In [2]: response.xpath('//*[@id="business-accreditation-content"]/p[2]').extract()
    Out[2]: []
    

    是的,没错 - 如果有意外请求用户代理,则响应仅包含 123

    现在有了标题(注意指定的-s 命令行参数):

    $ scrapy shell 'http://www.bbb.org/central-western-massachusetts/business-reviews/auto-repair-and-service/toms-automotive-in-fitchburg-ma-211787' -s USER_AGENT='Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36'
    In [1]: response.xpath('//*[@id="business-accreditation-content"]/p[2]').extract()
    Out[1]: [u'<p itemprop="description">BBB has determined that Tom\'s Automotive meets <a href="http://www.bbb.org/central-western-massachusetts/for-businesses/about-bbb-accreditation/bbb-code-of-business-practices-bbb-accreditation-standards/" lang="LS30TPCERNY5b60c87311af50cf82720b237d8ef866">BBB accreditation standards</a>, which include a commitment to make a good faith effort to resolve any consumer complaints. BBB Accredited Businesses pay a fee for accreditation review/monitoring and for support of BBB services to the public.</p>']
    

    这是一个来自 shell 的示例。在真正的 Scrapy 项目中,您需要设置 USER_AGENT project setting。或者,您也可以借助以下中间件使用用户代理轮换:scrapy-fake-useragent

    【讨论】:

      猜你喜欢
      • 2021-12-20
      • 1970-01-01
      • 2021-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-30
      相关资源
      最近更新 更多