python发布带有python请求的数据

时间:2014-11-19 09:45:29

标签: python login http-post python-requests

如果我尝试登录我的帐户并且不成功,那么我会在网址源页面中使用短语try again。所以我尝试编写python脚本来登录我的帐户并做一些事情:

更新

token=...#by xpath
session=requests.Session('http://example.com')
response=session.get('http://example.com')
cook=session.cookies
postdata={'token':token, 'arg1':'', 'arg2':'', 'name[user]': user, 'name[password]':password, 'arg3': 'Sign in'}
postresp=requests.post(url='http://example.com/sth', cookies=cook, data=post_data)
print postresp.content

postdata等有什么问题吗?

我还坐着饼干。

2 个答案:

答案 0 :(得分:1)

如果我要这样做,第一步是打开Chrome(如果你愿意,还是FF)并发送请求

F12 enter image description here

点击该特定请求,此处我只是刷新此页面,对您而言,这是登录请求 enter image description here

你可以看到需要什么,总有饼干,只需在模仿请求时使用这些cookie。有时只复制和粘贴cookie不起作用,如果是这样,你必须明确这些cookie的每个字段的含义,并自己制作一个。

祝你好运。

答案 1 :(得分:1)

你不想显示网址 - 没有它就很难击中靶心: - )

我的尝试告诉我是否有效,或者请注意您之后收到的错误。

Please note the following points: -try to use a user agent in the headers -Token needs to be fetched after calling the url (In the following case its the 5th line)

session=requests.Session()
headers={"User-Agent":"Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36"}
session.headers.update(headers)
response=session.get('http://example.com').content #I added this line
tree=html.fromstring(cont)                         #and this line 
token=tree.xpath('//*[@class="blah blah blah"]')
#cook=session.cookies -- You don't need this if you are continuing with the same session
postdata={'token':token, 'arg1':'', 'arg2':'', 'name[user]': user, 'name[password]':password, 'arg3': 'Sign in'}
postresp=session.post(url='http://example.com/sth', data=post_data) # use session.post instead of making a completely new request
print postresp.content

此外,如果有,请检查是否有具体的content-type,然后请将其添加到标题中

希望有所帮助: - )

相关问题