【发布时间】:2021-02-23 16:25:16
【问题描述】:
我正在尝试向德国的联邦机构索取数据。我首先必须在 HTML 表单上发送一个 post 请求,然后请求一个带有 CSV-Download 的 URL。 打开 Requests.Session() 后,发送 POST 请求没有问题,但我必须使用用户代理设置标头。
当之后尝试使用 requests.get 获取 CSV 时,我需要再次提供标头(否则我将被阻止)以及 JSESSIONID 以便网站知道我正在请求哪些数据(通过填写 HTML更早的形式)。
我面临的问题是,当我使用用户代理设置标头时,在我的 GET 请求中,我的 JSESSIONID 发生了变化。当我不设置标头时,JSESSIONID 保持不变,但我因未提供用户代理而被阻止。
我面临什么问题/我做错了什么?
正如您所测试的,当从r2 = s.get(csv_url, headers=headers) 行中删除headers=headers 时,JSESSIONID 是相同的。但是如果没有标头,网站会阻止我的请求。
import requests
s = requests.Session()
headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:12.0) Gecko/20100101 Firefox/12.0'}
api_url = "https://foerderportal.bund.de/"
url_post = api_url + "foekat/jsp/SucheAction.do?actionMode=searchlist"
csv_url = api_url + "foekat/jsp/SucheAction.do?actionMode=print&presentationType=csv"
# Sending the HTML form
payload = {"suche.bundeslandSuche[0]": "Hessen"}
r = s.post(url_post, data=payload, headers=headers)
print(s.cookies)
# Requesting the CSV
r2 = s.get(csv_url, headers=headers)
print(s.cookies)
# Writing the file
with open("test.csv", "w") as file:
file.write(r2.text)
【问题讨论】: