从嵌套的span标记中获取数据

时间:2015-12-23 21:31:21

标签: python urllib

我正在尝试使用此网站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)

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

2 个答案:

答案 0 :(得分:3)

事实上,您无法从相关网站获取此温度数据,因此不会将其作为静态html包含在内。您的原始正则表达式有效,但它正在查找文本temp +'°С或其附近,这是一个javascript函数。

你可以使用Selenium,但是从Javascript函数获取的数据中获取数据要容易得多,OpenWeatherMap API:

import urllib
import json

place = "Santa Monica"
apiurl = "http://api.openweathermap.org/data/2.5/weather?q={}&appid=2de143494c0b295cca9337e1e96b00e0".format(urllib.quote(place))

jsonfile = urllib.urlopen(apiurl)
jsontext = jsonfile.read()
result = json.loads(jsontext)

temp_K = result['main']['temp']
temp = (temp_K - 273.15)*(9/5) + 32
print(temp)

请注意温度以开尔文回归。这给你:

49.51

今天在圣莫尼卡感到寒冷:)

[删除了基于BeautifulSoup的原始答案,因为DOM元素是由Javascript生成的,所以它不起作用,因此它不存在于静态HTML中]

答案 1 :(得分:2)

为什么不使用他们的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:)

相关问题