Skip to main content
 首页 » 编程设计

Python:解析一个类什么都不打印

2024年10月25日11zlslch

尝试解析天气页面并选择每周预报最高点。

通常我会使用 tags = soup.find_all("span", id="hi") 进行搜索,但是这个标签不使用 id 它使用类。

完整代码:

import mechanize 
from bs4 import BeautifulSoup 
 
my_browser = mechanize.Browser() 
html_page = my_browser.open("http://www.wunderground.com/weather-forecast/45056") 
html_text = html_page.get_data() 
my_soup = BeautifulSoup(html_text) 
 
tags = my_soup.find_all("span", class_="hi") 
 
temp = tags[0].string 
print temp 

当我运行它时,没有打印任何内容

这段HTML隐藏在一堆其他的标签中,但是今天high的具体标签如下:

<span class="hi">63</span> 

请您参考如下方法:

只需使用class_ 作为参数名。参见 the docs.

问题的出现是因为class是Python关键字,不能直接使用。