为什么我的Scrapy代码返回一个空数组?

时间:2015-07-02 17:33:09

标签: python xpath web-scraping scrapy scrapy-spider

我正在为wunderground.com构建一个web scraper,但是我的代码返回" []"对于inches_rain和湿度。有人能看出为什么会这样吗?

# -*- 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()
            item['description'] = i.xpath('div/div/div/div/span/text()').extract()
            item['description'] = item['description'][0]
            item['humidity'] = i.xpath('div/table/tbody/tr/td/span/span/text()').extract()
            item['inches_rain'] = i.xpath('div/table/tbody/tr/td/span/span/text()').extract()
            list.append(item)
        return list

我也知道湿度和inches_rain项目设置为相同的xpath,但这应该是正确的,因为一旦信息在数组中,我只需将它们设置为数组中的某些值。

1 个答案:

答案 0 :(得分:5)

让我建议一个更可靠和可读的XPath来定位,例如,“湿度”值,其中基数是“湿度”列标签:

"".join(i.xpath('.//td[dfn="Humidity"]/following-sibling::td//text()').extract()).strip()

现在输出45%。

仅供参考,您的XPath至少有一个问题 - tbody标记 - 从XPath表达式中删除它。

相关问题