我正在尝试使用此网站http://openweathermap.org/find?q=获取天气数据,而我需要的信息位于以下代码中:

<p>
 <span class="badge badge-info">6.2°С </span>
 " temperature from 5 to 7.8°С, wind 1.17m/s. clouds 0%, 1031 hpa"
</p>


我正在使用以下机制来做到这一点:

import urllib
url = 'http://openweathermap.org/find?q=' + str(b)
htmlfile = urllib.urlopen(url)

htmltext = htmlfile.read()

regex = '<span class="badge badge-info">(.+?)</span>'

pattern = re.compile(regex)

temp = re.findall(pattern,htmltext)

print temp


但是我得到的结果是这样的:

["'+temp +'\xc2\xb0\xd0\xa1 "]


我搜索的每个关键字都是一样的(上面的b)

我究竟做错了什么?另外,如何获取段落标记中包含的其余信息?提前致谢

最佳答案

为什么不使用他们的JSON API而不是解析HTML?这样会容易得多。您将拥有所有可用数据,并且可以使用该数据重建段落。

import json
import urllib

url = 'http://api.openweathermap.org/data/2.5/weather?units=metric&q=' + str(b)
request = urllib.urlopen(url)
text = request.read()

data = json.loads(text)

print u"{}\xb0C from {} to {}\xb0C, wind {}m/s, clouds {}%, {} hpa".format(
    data['main']['temp'], data['main']['temp_min'], data['main']['temp_max'],
    data['wind']['speed'], data['clouds']['all'], data['main']['pressure'])


您可以在此处阅读有关其API的更多信息:http://openweathermap.org/api

编辑:在字符串中添加°C :)

关于python - 从嵌套span标签获取数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34444039/

10-11 19:38
查看更多