用美丽的汤刮网页



我是网络抓取的新手,我正在尝试从网站上抓取wind数据。以下是网站:https://wx.ikitesurf.com/spot/507.我知道我可以用硒来寻找元素,但我想我可能找到了更好的方法。如果我错了,请纠正。当在开发人员工具中时,我可以通过转到网络找到此页面->JS->getGraph?

https://api.weatherflow.com/wxengine/rest/graph/getGraph?callback=jQuery17200020271765600428093_1619158293267&units_wind=英里/小时&units_temp=f&units_distance=mi&fields=wind&format=json&min_from_now=60&show_virtual_obs=true&spot_ id=507&time_start_offset_hours=-36&time_end_offset_hours=0&type=dataonly&model_ids=-101&wf_token=3a648ec44797cbf12aca8ebc6c538868&amp_=1619158293881

这个页面包含了我需要的所有数据,并且不断更新。这是我的代码:

url = 'https://api.weatherflow.com/wxengine/rest/graph/getGraph?callback=jQuery17200020271765600428093_1619158293267&units_wind=mph&units_temp=f&units_distance=mi&fields=wind&format=json&null_ob_min_from_now=60&show_virtual_obs=true&spot_id=507&time_start_offset_hours=-36&time_end_offset_hours=0&type=dataonly&model_ids=-101&wf_token=3a648ec44797cbf12aca8ebc6c538868&_=1619158293881'
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")
time.sleep(3)
wind = soup.find("last_ob_wind_desc")
print (wind)

我试着用漂亮的汤刮,但我总是收到答案";无";。有人知道我怎样才能把这一页刮下来吗?我想知道我做错了什么。谢谢你的帮助!

apiurl中删除callback=jQuery17200020271765600428093_1619158293267&将使其返回正确的json:

import requests
url = 'https://api.weatherflow.com/wxengine/rest/graph/getGraph?units_wind=mph&units_temp=f&units_distance=mi&fields=wind&format=json&null_ob_min_from_now=60&show_virtual_obs=true&spot_id=507&time_start_offset_hours=-36&time_end_offset_hours=0&type=dataonly&model_ids=-101&wf_token=3a648ec44797cbf12aca8ebc6c538868&_=1619158293881'
response = requests.get(url).json()

response现在是一个包含数据的字典。CCD_ 4可以用CCD_。

您还可以使用pandas:将数据保存为csv或其他文件格式

import pandas as pd
df = pd.json_normalize(response)
df.to_csv('filename.csv')

最新更新