python用python中的请求发布数据

2024-10-01 15:37:43 发布

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

如果我尝试登录到我的帐户,但没有成功,那么我将在url源页面中使用短语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或etc有什么问题吗?在

我也吃饼干。在


Tags: namecomtokenhttpurlexamplesession帐户
2条回答

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

这是我的尝试,让我知道它是否有效,或请评论你的错误后,这里。在

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如果有,请将其添加到标题中

希望有帮助:-)

如果我要这样做,第一步是打开Chrome(或者如果你喜欢的话,也可以是FF)并发送一个请求

按F12键 enter image description here

点击那个特定的请求,这里我只是刷新这个页面,对你来说,这是登录请求 enter image description here

你可以看到需要什么,总是有cookies,当你模仿请求时就使用这些cookie。有时候只复制和粘贴cookies是行不通的,如果是这样的话,你必须弄清楚这些cookies的每个字段的含义,并自己制作一个。在

祝你好运。在

相关问题 更多 >

    热门问题