首页 > 解决方案 > 如何使用漂亮的汤从实时网站记录数据

问题描述

您好,我正在尝试使用漂亮的汤并请求记录来自每秒实时更新的风速计的数据。这个网站的链接在这里:

http://88.97.23.70:81/

我要抓取的数据在图像中以紫色突出显示:

随附的

通过在我的浏览器中检查 html。

我已经编写了下面的代码以尝试打印出数据,但是当我运行它打印的代码时None:我认为这意味着汤对象实际上并不包含整个 html 页面?打印时,我在浏览器中检查 html 时soup.prettify()找不到相同的内容。id=js-2-text如果有人知道为什么会这样或如何解决它,我将不胜感激。

from bs4 import BeautifulSoup
import requests

wind_url='http://88.97.23.70:81/'
   
r = requests.get(wind_url)
data = r.text
soup = BeautifulSoup(data, 'lxml')
           
print(soup.find(id='js-2-text'))

一切顺利,布伦丹

标签: pythonbeautifulsouppython-requestspython-requests-html

解决方案


数据是从外部 URL 加载的,所以 beautifulsoup 不需要它。您可以尝试使用页面连接到的 API URL:

import requests
from bs4 import BeautifulSoup


api_url = "http://88.97.23.70:81/cgi-bin/CGI_GetMeasurement.cgi"
data = {"input_id": "1"}

soup = BeautifulSoup(requests.post(api_url, data=data).content, "html.parser")
_, direction, metres_per_second, *_ = soup.csv.text.split(",")

knots = float(metres_per_second) * 1.9438445

print(direction, metres_per_second, knots)

印刷:

210 006.58 12.79049681

推荐阅读