Skip to main content
 首页 » 编程设计

python之带有 scrapy 和 Xpath 的空列表

2024年10月24日13jyk

我开始使用 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 Accreditation

A BBB Accredited Business since 02/12/2010

BBB has determined that Tom's Automotive meets BBB accreditation standards, which include a commitment to......"

这一段的xpath是:

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

所以我使用:

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

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

请您参考如下方法:

该网站实际检查 User-Agent header 。

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

$ 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。

现在有了 header (注意指定的 -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 .