Skip to main content
 首页 » 编程设计

python之从嵌套的 span 标签获取数据

2025年05月04日30artech

我正在尝试使用此网站获取天气数据 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)

我做错了什么?另外我怎样才能得到段落标签中包含的其余信息?提前致谢

请您参考如下方法:

事实上,您无法从相关站点获取此温度数据,它没有作为静态 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 中]