【问题标题】:Scraping Webpage With Beautiful Soup用漂亮的汤刮网页
【发布时间】:2021-04-23 06:54:08
【问题描述】:

我是网络抓取的新手,我正在尝试从网站抓取风数据。这是网站:https://wx.ikitesurf.com/spot/507。 我知道我可以使用 selenium 来查找元素,但我想我可能找到了更好的方法。如果我错了,请纠正。在开发者工具中,我可以通过 network->JS->getGraph 找到这个页面?

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

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

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)

我试过用漂亮的汤来刮,但我总是得到“无”的答案。有谁知道我怎样才能刮掉这个页面?我想知道我做错了什么。感谢您的帮助!

【问题讨论】:

  • 问题是响应不是html。 content-type 是application/x-javascript,所以你应该使用另一个解析器或库来读取数据。

标签: python json selenium screen-scraping


【解决方案1】:

api url 中删除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 现在是一个包含数据的字典。 last_ob_wind_desc 可以用response['last_ob_wind_desc'] 检索。

您也可以将数据保存为csvpandas的其他文件格式:

import pandas as pd

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

【讨论】:

  • 没错!我同意你的做法。
  • 成功了!我一直在尝试使用 selenium 解决一个星期,但这要好得多。非常感谢您的帮助。
猜你喜欢
  • 2017-08-15
  • 1970-01-01
  • 2012-08-01
  • 2020-08-09
  • 2017-12-23
  • 2021-04-07
  • 2020-06-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多