【问题标题】:Xpath selector not working in ScrapyXpath 选择器在 Scrapy 中不起作用
【发布时间】:2016-09-20 09:44:08
【问题描述】:

我正在尝试从此 Xpath 中提取文本:

//*/li[contains(., "Full Name")]/span/text()

来自此网页: http://votesmart.org/candidate/biography/56110/norma-smith#.V9SwdZMrKRs

我已经在 Google Chrome 的控制台(可以工作)中测试了它,就像 Xpath 的许多其他变体一样,但我无法让它与 Scrapy 一起使用。我的代码只返回“{}”。

这是我在代码中测试它的地方,用于上下文:

 def parse_bio(self, response):  
    loader = response.meta['loader']
    fullnameValue = response.xpath('//*/li[contains(., "Full Name")]/span/text()').extract()
    loader.add_value('fullName', fullnameValue)
    return loader.load_item()

问题不在于我的代码(我不认为),它适用于其他(非常广泛的)Xpath 选择器。但我不确定 Xpath 有什么问题。我禁用了 JavaScript,如果这有什么不同的话。 任何帮助都会很棒!

编辑:为了更清楚,这里是其余的代码:

from scrapy import Spider, Request, Selector
from votesmart.items import LegislatorsItems, TheLoader



class VSSpider(Spider):
name = "vs"
allowed_domains = ["votesmart.org"]
start_urls = ["https://votesmart.org/officials/WA/L/washington-state-legislative"]


def parse(self, response):
    for href in response.xpath('//h5/a/@href').extract():
        person_url = response.urljoin(href)
        yield Request(person_url, callback=self.candidatesPoliticalSummary)

def candidatesPoliticalSummary(self, response): 
    item = LegislatorsItems()
    l = TheLoader(item=LegislatorsItems(), response=response)


   ...
   #populating items with item loader. works fine

    # create right bio url and pass item loader to it
    bio_url = response.url.replace('votesmart.org/candidate/', 
                                   'votesmart.org/candidate/biography/')
    return Request(bio_url, callback=self.parse_bio, meta={'loader': l})

def parse_bio(self, response):  
    loader = response.meta['loader']
    print response.request.url
    loader.add_xpath('fullName', '//*/li[contains(., "Full Name")]/span/text()')
    return loader.load_item()

【问题讨论】:

    标签: xpath scrapy


    【解决方案1】:

    我发现了我的问题!网站上的许多页面都受到登录保护,我无法从一开始无法访问的页面中抓取。 Scrapy 的表单请求成功了。感谢所有帮助(尤其是使用view(response) 的建议,非常有帮助)。

    【讨论】:

      【解决方案2】:

      表达式在 shell 中完美地为我工作:

      $ scrapy shell "http://votesmart.org/candidate/biography/56110/norma-smith#.V9SwdZMrKRs"
      In [1]: response.xpath('//*/li[contains(., "Full Name")]/span/text()').extract()
      Out[1]: [u'Norma Smith']
      

      尝试改用add_xpath() 方法:

      loader.add_xpath('fullName', '//*/li[contains(., "Full Name")]/span/text()')
      

      【讨论】:

      • 我尝试了 add_xpath 方法,它仍然对我不起作用。在我打印/检查响应 url 的方法中,问题也不是 url。
      • @KatherineCavanaugh 我也检查过了,xpath 工作正常。您确定可以正确下载该页面吗?一旦你scrapy shell url 你会得到200 状态码吗?尝试在您的浏览器中禁用 javascript 并调用 view(response) 并在您的浏览器中查看该页面(如果它没有丢失任何内容)。您的来源可能由于某种原因而失真。还有可能是这个网站屏蔽了你。
      猜你喜欢
      • 1970-01-01
      • 2023-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多