Reputation: 5972
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:
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
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
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
Click that specific request, here I just refresh this page, for you, it's the login request
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