【问题标题】:How to use BeautifulSoup to extract data outside of html tags如何使用 BeautifulSoup 提取 html 标签之外的数据
【发布时间】:2014-09-28 17:03:01
【问题描述】:

我是 python 和 SO 的新手。这是我的问题。

我正在尝试从以下网页NDBC - Station 46011. 中提取数据我一直在观看有关如何使用 BeautifulSoup 从网页中收集数据的教程,到目前为止我有以下代码:

import requests
from bs4 import BeautifulSoup
url = 'http://www.ndbc.noaa.gov/data/latest_obs/46011.rss'
r = requests.get(url)
soup = BeautifulSoup(r.content)
data_types = soup.find_all('strong')
for item in data_types:
    print(item.text) 

这为我提供了不同的数据类型(风向、速度、阵风等)。但是,我无法从此网页中提取数字数据。当您查看网页源代码时,您可以看到数字数据位于“strong”标签之后和“br”标签之前。由于它没有明确位于两个标签之间,因此我无法提取此数据。

提前感谢您的所有帮助!

【问题讨论】:

标签: python html beautifulsoup


【解决方案1】:
import requests
from bs4 import BeautifulSoup
url = 'http://www.ndbc.noaa.gov/data/latest_obs/46011.rss'
r = requests.get(url)
soup = BeautifulSoup(r.content)
data_types = soup.find_all("description")[1].text.split('\n')
for item in data_types:
    print(item)

Out[1]:
September 28, 2014 12:50 am PDT
Location: 35N 120.992W
Wind Direction: NW (320°)
Wind Speed: 7.8 knots
Wind Gust: 9.7 knots
Significant Wave Height: 8.5 ft
Dominant Wave Period: 9 sec
Average Period: 6.7 sec
Mean Wave Direction: NW (304°) 
Atmospheric Pressure: 29.90 in (1012.5 mb)
Pressure Tendency: +0.00 in (+0.0 mb)
Air Temperature: 62.1°F (16.7°C)
Water Temperature: 59.9°F (15.5°C)

希望有所帮助:-)

如果您还需要进一步的步骤,请告诉我。

【讨论】:

    【解决方案2】:

    如果您只想在每个 <strong> 标记(并且您确定在 <strong> 之后总是有一些文本)旁边的文本(不在标记内),您可以操作 BeautifulSoup 的 contents 列表。下面的代码为您提供了元组列表中数据项的标签和内容。

    import requests
    from bs4 import BeautifulSoup
    url = 'http://www.ndbc.noaa.gov/data/latest_obs/46011.rss'
    r = requests.get(url)
    soup = BeautifulSoup(r.content)
    contents = soup.find_all('description')[1].contents
    data=[]
    for i,content in enumerate(contents):
        if content.name=="strong":
            data.append((content.string,contents[i+1].string))
    print data    
    

    输出:

    [(u'Location:', u' 35N 120.992W'), (u'Wind Direction:', u' NW (320\xb0)'), (u'Wind Speed:', u' 7.8 knots'), (u'Wind Gust:', u' 9.7 knots'), (u'Significant Wave Height:', u' 8.5 ft'), (u'Dominant Wave Period:', u' 9 sec'), (u'Average Period:', u' 6.7 sec'), (u'Mean Wave Direction:', u' NW (304\xb0) '), (u'Atmospheric Pressure:', u' 29.90 in (1012.5 mb)'), (u'Pressure Tendency:', u' +0.00 in (+0.0 mb)'), (u'Air Temperature:', u' 62.1\xb0F (16.7\xb0C)'), (u'Water Temperature:', u' 59.9\xb0F (15.5\xb0C)')]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-05
      • 2015-10-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多