Python:解析 class 什么都不打印?

Python: Parsing a class prints nothing?

正在尝试解析天气页面和select每周预报的最高气温。

通常我会使用 tags = soup.find_all("span", id="hi") 进行搜索,但此标签不使用 id,而是使用 class.

完整代码:

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这块被其他标签埋没了,不过今天高点的具体标签如下:

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

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

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

作为抓取网页的替代方法,您可以随时查看 Weather Underground 的 API。它对开发人员免费(每天调用次数有限等),但如果您要进行多次查找,最后这可能会更容易。