Python-Requests Post请求失败,403 Forbidden

时间:2016-12-02 22:26:12

标签: python-2.7 python-requests

我试图使用python-requests登录https://www.custommade.com/,但它一直给我一个“403禁止错误”。我从httpfox

获得了post_url和有效载荷的内容
import requests

post_url = 'https://www.custommade.com/secure/login/api/'

client = requests.session()

csrftoken = client.get('https://www.custommade.com/').cookies['csrftoken']

header_info = {
    'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36',
    'Content-type': 'application/json'
    }

payload = {'_method':'login','csrftoken': csrftoken,'email': MYEMAIL,'password':MYPWS} 

r = client.post(post_url, json=payload, headers = header_info)

print r.status_code

有人可以帮忙吗?我试图登录其他网站,这很好。

1 个答案:

答案 0 :(得分:1)

如果您要打印您收到的回复文本,您会看到他们向您显示您不接受Cookie的错误。

当你做这样的事情时 - 总是尝试尽可能地模拟浏览器 - 这意味着你必须设置所有标题并执行浏览器所做的步骤。

首先在浏览器中打开网页。打开开发工具,网络选项卡。 现在点击登录 - >你看到浏览器确实向/ secure / proxy请求了 所以你的程序也必须这样做。比实际要求。确保您的请求看起来与浏览器的请求相同 - 检查标题。你可以看到他们在那里发送令牌。 (顺便说一句,他们不像你在脚本中那样在发布数据中发送它)。他们也可能会检查一些其他标题,因为当你删除它们时 - 它不起作用。最简单的方法是将所有标题都设置为浏览器。

别忘了饼干。但这是自动完成的,因为您正在使用来自请求的会话。

enter image description here

无论如何这是工作代码:

import requests

post_url = 'https://www.custommade.com/secure/login/api/'


client = requests.session()

client.get('https://www.custommade.com/')
r = client.get('https://www.custommade.com/secure/proxy/')

csrftoken = r.cookies['csrftoken']


header_info = {
"Host" : "www.custommade.com",
"Connection" : " keep-alive",
"Origin" : " https://www.custommade.com",
"User-Agent" : " Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36",
"Content-Type" : " application/x-www-form-urlencoded",
"Accept" : " */*",
"X-Requested-With" : " XMLHttpRequest",
"X-CSRFToken" : csrftoken,
"DNT" : " 1",
"Referer" : " https://www.custommade.com/secure/proxy/",
"Accept-Encoding" : " gzip, deflate, br",
"Accept-Language" : " en-US,en;q=0.8,cs-CZ;q=0.6,cs;q=0.4,sk;q=0.2,ru;q=0.2",
}



payload = {'_method':'login','email': 'sdfasdf@safs.com','password':'asfdasf', 'remember':True} 

r = client.post(post_url, data=payload, headers = header_info)

print r.text
print r.status_code

打印:

{"errors": "Oops! Something went wrong.  Please ensure you are sending JSON data."}
400

^^表示密码错误

相关问题