Python使用lxml解析来自站点的数据
我是Python新手。这就是我请求帮助的原因。 我需要解析来自站点的ssome数据。我正在使用Python 2.7。 这是我的代码:Python使用lxml解析来自站点的数据,python,parsing,python-2.7,lxml,Python,Parsing,Python 2.7,Lxml,我是Python新手。这就是我请求帮助的原因。 我需要解析来自站点的ssome数据。我正在使用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
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
文件“weather.py”,第15行,打印(“%s,%s%”(温度[0],云[0]))
索引器:列表索引超出范围
这是因为您的温度和云是空列表。
只包含内容。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]))
导入urllib
导入lxml.html
#pageReady=u'content.decode()'可能比解析为人类提供的html更健壮。