use*_*157 33 python cookies python-requests
我正在尝试登录页面并访问页面中的其他链接.
payload={'username'=<username>,'password'=<password>}
with session() as s:
r = c.post(<URL>, data=payload)
print r
print r.content
Run Code Online (Sandbox Code Playgroud)
这给了我一个"405 Not Allowed"错误.我使用chrome开发人员工具查看了post方法的详细信息,可以看到api(URL/api/auth).我使用有效负载发布到该URL,它正在工作,我收到类似于我在开发人员中看到的响应.
不幸的是,在登录后尝试"获取"另一个URL时,我仍然从登录页面获取内容.为什么登录不坚持?我应该使用cookies吗?我是新手,所以我真的不知道如何使用cookies.
gta*_*ico 53
您可以使用会话对象.它存储cookie以便您提出请求,并为您处理cookie
s = requests.Session()
# all cookies received will be stored in the session object
s.post('http://www...',data=payload)
s.get('http://www...')
Run Code Online (Sandbox Code Playgroud)
文档:http://docs.python-requests.org/en/latest/user/advanced/
您还可以将cookie数据保存到外部文件,然后重新加载它们以保持会话持久性,而无需在每次运行脚本时登录:
Fre*_*jer 21
从文档:
从响应中获取cookie
url = 'http://example.com/some/cookie/setting/url'
r = requests.get(url)
r.cookies
Run Code Online (Sandbox Code Playgroud)
{'example_cookie_name': 'example_cookie_value'}
在后续请求中将cookie返回给服务器
url = 'http://httpbin.org/cookies'
cookies = dict(cookies_are='working')
r = requests.get(url, cookies=cookies)`
Run Code Online (Sandbox Code Playgroud)总结(@Freek Wiekmeijer,@gtalarico)其他人的回答:
authentication,然后才能访问,否则405 Not Allowedauthentication=grant access方法有:
cookieauth header
Basic xxxAuthorization xxxcookie在requests与AUTHcookie在headerscookie由requests's
自动处理session 自动管理cookiesresponse.cookies 手动设置 cookierequests的session自动管理cookiescurSession = requests.Session()
# all cookies received will be stored in the session object
payload={'username': "yourName",'password': "yourPassword"}
curSession.post(firstUrl, data=payload)
# internally return your expected cookies, can use for following auth
# internally use previously generated cookies, can access the resources
curSession.get(secondUrl)
curSession.get(thirdUrl)
Run Code Online (Sandbox Code Playgroud)
requests的response.cookiespayload={'username': "yourName",'password': "yourPassword"}
resp1 = requests.post(firstUrl, data=payload)
# manually pass previously returned cookies into following request
resp2 = requests.get(secondUrl, cookies= resp1.cookies)
resp3 = requests.get(thirdUrl, cookies= resp2.cookies)
Run Code Online (Sandbox Code Playgroud)
小智 6
正如其他人指出的,这是如何将 cookie 作为字符串变量添加到 headers 参数的示例 -
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) ...",
"cookie": "_fbp=fb.1.1654447470850.2143140577; _ga=GA1.2.1...",
}
response = requests.get(url, headers=headers)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
83047 次 |
| 最近记录: |