【问题标题】:Python Parsing data from site using lxmlPython使用lxml从站点解析数据
【发布时间】:2013-12-01 04:59:22
【问题描述】:

我是 Python 新手。这就是我寻求帮助的原因。 我需要从站点解析一些数据。我正在使用 Python 2.7。 所以这是我的代码:

import urllib
import lxml.html

url = 'http://www.pogoda.YANDEX.RU/MOSCOW'
sock = urllib.urlopen(url)
content = sock.read()
pageReady = u'content.decode()'
page = urllib.urlopen('http://pogoda.yandex.ru/moscow/')
xmldata = lxml.html.document_fromstring(pageReady)
temperature = xmldata.xpath('//div[@class="b-thermometer__now"]/text()')              
clouds = xmldata.xpath('//div[@class="b-info-item b-info-item_type_fact-big"]/text()')
sock.close()

print('%s, %s'%(temperature[0], clouds[0])) 

所以我收到了下一条消息:

File "weather.py", line 15, in <module> print('%s, %s'%(temperature[0], clouds[0])) 
IndexError: list index out of range 

【问题讨论】:

标签: python parsing python-2.7 lxml


【解决方案1】:

pageReady 仅包含 content.decode() 作为其内容,因为以下行:

pageReady = u'content.decode()'

您应该使用page.read() 获取网页内容如下:

import urllib
import lxml.html

# pageReady = u'content.decode()'   <----------- Remove/comment out this line.
page = urllib.urlopen('http://pogoda.yandex.ru/moscow/')
pageReady = page.read()   # <-------------------------------
xmldata = lxml.html.document_fromstring(pageReady)
temperature = xmldata.xpath('//div[@class="b-thermometer__now"]/text()')              
clouds = xmldata.xpath('//div[@class="b-info-item b-info-item_type_fact-big"]/text()')
page.close()

print('%s, %s'%(temperature[0], clouds[0])) 

【讨论】:

    【解决方案2】:

    这是因为您的 temperatureclouds 是空列表。

    【讨论】:

      猜你喜欢
      • 2019-02-27
      • 2012-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-13
      • 2013-12-23
      相关资源
      最近更新 更多