【问题标题】:How to get data with requests while setting headers and JSESSIONID如何在设置标头和 JSESSIONID 时通过请求获取数据
【发布时间】: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)

【问题讨论】:

    标签: python python-requests


    【解决方案1】:

    默认用户代理是 python-requests/{version}

    一些网站阻止来自非网络浏览器用户代理的访问以防止抓取。

    您可以像这样为您的会话定义默认用户代理:

    import requests
    
    s = requests.Session()
    s.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)
    
    print(s.cookies)
    
    # Requesting the CSV
    r2 = s.get(csv_url)
    print(s.cookies)
    

    【讨论】:

    • 谢谢,解决了。不知道我必须将标题直接分配给会话。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-06
    • 2017-01-13
    • 1970-01-01
    • 1970-01-01
    • 2014-12-20
    • 2018-03-30
    相关资源
    最近更新 更多