python - 使用 Python 请求抓取航类数据

标签 python python-requests

以下 URL 显示航类并提供更多详细信息(例如在左侧切换“Flugweg”或“Statistik”)。我想读取这些数据,然后将其转换为列表。

https://www.onlinecontest.org/olc-2.0/gliding/flightinfo.html?dsId=6188729

所以到目前为止我一直在做以下事情:

import requests
API_url = "https://www.onlinecontest.org/olc-2.0/gliding/dataprov.html"
response = requests.post(API_url)

执行response.text会给我一个返回页面,基本上告诉我“请求的页面不存在”。

然后我尝试添加 header 信息,因为我读到有时这是请求被拒绝的原因:

headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36",
            "Referer":"https://www.onlinecontest.org/olc-2.0/gliding/flightinfo.html?dsId=6188729",
          "Origin":"https://www.onlinecontest.org"}

然后就有了

response = requests.post(API_url, headers = headers)

这并没有改变任何事情,只是浑水摸鱼。

使用 Chrome 搜索 XHR 会提供三个文件,它们包含我想要的内容,但我已经没有想法了,不知道如何获取它们。访问数据的正确方法是什么?

最佳答案

正如您所说,该页面发出 3 个 XHR 请求。您可以使用 POST 发出这些请求。您只需要获取有效负载的正确参数即可。您可以使用 BeautifulSoup 和 urllib 来完成此操作,如果您还没有安装,则可能需要安装它们。这是针对 Python 3 的,Python 2 有不同的 urllib 实现。

import requests
from bs4 import BeautifulSoup
from urllib.parse import urlparse, parse_qs

# Get the web page.
url = "https://www.onlinecontest.org/olc-2.0/gliding/flightinfo.html?dsId=6188729"
page = requests.get(url).text

# Extract the first parameter you need for the POST request from the URL.
parsed_url = urlparse(url)
id = parse_qs(parsed_url.query)['dsId'][0]
print (id) # 6188729

# Get the first XML.
payload = {'nature':'dsstat','id': id}
data1 = requests.post("https://www.onlinecontest.org/olc-2.0/gliding/dataprov.html", data =payload)
print (data1.text)

# Get the ref attribute for the second POST request using BeautifulSoup.
soup = BeautifulSoup(page, 'html.parser')
dsstat = soup.find("meta", {'name':"og:image"})
parsed_url = urlparse(dsstat['content'])
ref = parse_qs(parsed_url.query)['ref'][0]
print (ref) # 977301232

# Get the second XML.
payload = {'nature':'track','ref': ref}
data2 = requests.post("https://www.onlinecontest.org/olc-2.0/gliding/dataprov.html", data =payload)
print (data2.text)

# Get the thrd XML. The id is the first ID + 1.
id2 = (int (id) + 1)
print (id2) # 6188730
payload = {'nature':'dsstat','id':id2}
data3 = requests.post("https://www.onlinecontest.org/olc-2.0/gliding/dataprov.html", data =payload)
print (data3.text)

关于python - 使用 Python 请求抓取航类数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47728949/

相关文章:

python - 连接中断 : IncompleteRead(0 bytes read) when sending request to Django on Heroku

python - 使用 QtNetwork 和 PyQt5 检查互联网连接

python - Google Cloud Functions - 我可以将来自不同 GCP 项目存储库的代码部署到 Cloud Functions 中吗?

python - 通过索引/列元素连接数据帧

python - 如何确定在 Python 中使用 HTTP 下载的内容的文件名?

ssl - 如何更改/调整 Python 3.10 请求的默认 SSL 设置 - sslv3 警报握手失败

python - DNA 从字符串列表中找到所有匹配项 (python 2.7)

Python 多进程共享内存与使用参数

python - requests.get() 在 aws lambda 中抛出异常

python - bs4 丢弃特定标签之前的所有 HTML