如何确定正确的XPath?

时间:2015-07-09 18:16:24

标签: python xpath web-scraping scrapy

我正在Scrapy中为wunderground.com制作一个网络刮刀,但我选择的许多不同的XPath都会返回空数组。我在同一主题(here)上找到了一个不同的问题,这实际上是我将代码切换到wunderground.com的原因。但是,给出的答案专门针对一个确切的对象。我如何确定其他对象的正确XPath?

以下是代码:

# -*- coding: utf-8 -*-
import scrapy
from scrapy.selector import Selector
import time

from wunderground_scraper.items import WundergroundScraperItem

class WundergroundComSpider(scrapy.Spider):
    name = "wunderground"
    allowed_domains = ["www.wunderground.com"]
    start_urls = (
        'http://www.wunderground.com/q/zmw:10001.5.99999',
    )

    def parse(self, response):
        info_set = Selector(response).xpath('//div[@id="current"]')
        list = []
        for i in info_set:
            item = WundergroundScraperItem()
            # WORKS FINE
            item['temperature'] = i.xpath('div/div/div/div/span/span/text()').extract()
            item['temperature'] = item['temperature'][0]


            # EDITED XPATH FROM OTHER QUESTION
            item['humidity'] = i.xpath('.//td[dfn="Humidity"]/following-sibling::td//text()').extract()
            item['humidity'] = item['humidity'][2]


            # RETURNS EMPTY ARRAY
            item['chance_rain'] = i.xpath('div/div/div/div/a/strong/text()').extract()


            list.append(item)
        return list

1 个答案:

答案 0 :(得分:1)

通常,“如何确定正确的XPath表达式”的答案将是“通过检查”(即,查看您尝试查询的文档,或“通过反复试验”(从一般表达式开始,然后缩小它们直到得到你想要的东西。

在这种情况下,您遇到了一个非常常见的问题:您在浏览器中看到的页面使用Javascript部分呈现本地。包含降水机会的元素包含在<script>资源的一部分中,从XML解析器的角度来看,它是(a)简单的不透明文本块和(b)甚至不包含信息你正在寻找,因为它需要先由脚本填写。直到使用Javascript呈现页面时,才会在文档中实际实例化该元素。

无法从文档源中提取此数据。

相关问题