Python请求问题本身。\u存储[key.lower()][1]

2024-04-19 08:27:54 发布

您现在位置:Python中文网/ 问答频道 /正文

import requests
url = "url"
payload="payload"
headers= headers
response = requests.request("POST",url, headers=headers, data=payload)
authCode = response.headers['authentication]

wurl = "wurl"
wpayload = "wpayload"
wheaders = {
       'Cookie': 'Cookie',
       'User-Agent: 'User-Agent',
       'Authentication' : authCode,
        }

wresponse = requests.request("POST",wurl, headers=wheaders, data=wpayload)

您好,我使用Python请求模块编写了这样一个程序。问题是,我可以先从程序的头部分获取身份验证代码,然后才能使用它。但是我不能从第二部分的数据中得到我想要的数据。错误代码如下所示

Traceback (most recent call last):
  File "d:\requeststest\app.py", line 30, in <module>
    getdata = wresponse.headers['Id']
  File "C:\Users\Alp\AppData\Local\Programs\Python\Python39\lib\site-packages\requests\structures.py", line 54, in __getitem__
    return self._store[key.lower()][1]
KeyError: 'id'

虽然我在收到的数据中有ID信息,但当我试图获取ID信息时,会出现此错误。但是在第一个请求中,我能够以相同的方式从头部获取身份验证代码。你能帮忙吗


Tags: 数据urldatacookieresponserequestpostrequests
1条回答
网友
1楼 · 发布于 2024-04-19 08:27:54

请求是对案件不敏感的指令

type(wresponse.headers)
<class 'requests.structures.CaseInsensitiveDict'>

使用get方法从这个构造的dicts中获取项要好得多

wresponse = requests.get('https://www.google.es')
wresponse.headers
{'Date': 'Fri, 15 Jan 2021 21:39:46 GMT', 'Expires': '-1', 'Cache-Control': 'private, max-age=0', 'Content-Type': 'text/html; charset=ISO-8859-1', 'P3P': 'CP="This is not a P3P policy! See g.co/p3phelp for more info."', 'Content-Encoding': 'gzip', 'Server': 'gws', 'X-XSS-Protection': '0', 'X-Frame-Options': 'SAMEORIGIN', 'Set-Cookie': 'NID=207=gnRg4009rRe7v_PKYtq-3lb3ouJVNAvRpV7VsORkV2OSMkEyb_2s4GGhMIGIST9yN6ecbIzmFVbuGxXUn9mB5ourXONKakngjf4BZ_K31C4908P_VJCzPitnW-LliA-jZZb0vwQwPWhkrGyTnd8tqhZsmh0z1ftxKwvPURJyzdw; expires=Sat, 17-Jul-2021 21:39:46 GMT; path=/; domain=.google.es; HttpOnly', 'Alt-Svc': 'h3-29=":443"; ma=2592000,h3-T051=":443"; ma=2592000,h3-Q050=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000,quic=":443"; ma=2592000; v="46,43"', 'Transfer-Encoding': 'chunked'}

wresponse.headers.get('Date')
'Fri, 15 Jan 2021 21:39:46 GMT'

但是,您的错误是Id键不存在。 尝试使用wresponse.headers.keys()print(wresponse.headers)并验证

祝你好运

相关问题 更多 >