Python-HTML-如何使用BeautifulSoup去除标记之间的内容

时间:2013-07-19 02:19:23

标签: python html parsing beautifulsoup

我在做什么:我正在编写一个网页提取器来收集天气数据。这就是我到目前为止所做的:

import urllib.request
from bs4 import BeautifulSoup

# open the webpage and assign the content to a new variable
base = urllib.request.urlopen('http://www.weather.com/weather/today/Beijing+CHXX0008:1:CH')
f = base.readlines()
f = str(f)


soup = BeautifulSoup(f)

rn_base = soup.find_all(itemprop="temperature-fahrenheit")

如果您print变量rn_base,则会得到:[<span class="wx-value" itemprop="temperature-fahrenheit">75</span>],我认为这是一个只包含一个元素的列表。数字75是我的目标。

问题:我尝试了几种方法来获取号码但失败了。它们是1)使用str.join()rn_base转换为字符串,但由于rn_baseResultSet对象而失败; 2)使用索引切片,但因为它不是字符串主题,失败。 3)使用beautifulsoup documentation中指定的get_text(),但获得AttributeError: 'ResultSet' object has no attribute 'get_text'

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

rn_base是一个 resultSet 对象,所以即使结果只是一个,它也会假设结果可能很多。所以,

for rn in rn_base
Print rn.string

这个for循环将从结果中提取每一行(当它们多次出现“温度 - 华氏度”时)

正如您所说的尝试天气数据我认为最好使用find(),其限制超过find_all()