MLSC
MLSC

Reputation: 5972

python post data with requests in python

If I try to login to my account and it is not successful then I would have phrase try again in url source page. So I tried to write python script to login to my account and do stuff:

Update

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

Is there something wrong with postdata or etc?

I also sat cookies.

Upvotes: 0

Views: 494

Answers (2)

Md. Mohsin
Md. Mohsin

Reputation: 1832

You don't want to show the url - and its difficult to hit the bulls eye without it:-)

Here's my try let me know if it works or please comment with the error you get here after.

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

Also, please check if there is specific content-type if yes, then please add it to the headers

Hope that helps :-)

Upvotes: 1

laike9m
laike9m

Reputation: 19328

If I were going to do this, the first step is open Chrome(or FF if you like) and send a request

Press F12 enter image description here

Click that specific request, here I just refresh this page, for you, it's the login request enter image description here

And you could see what's needed, there are always cookies, and just use these cookies when you imitate the request. Sometimes only copy and pasting cookies won't work, if so, you have to make clear the meaning of every field of those cookies, and make one yourself.

Good luck.

Upvotes: 1

Related Questions