1

I have this code:

import requests

url = 'https://mobile.twitter.com/session/new'

payload = {
       'username': 'username',
       'password': 'password',
       }
with requests.Session() as c:
    c.post(url, data=payload)
    r = c.get('https://mobile.twitter.com/account')
    print 'username' in r.content

The goal is to login to twitter mobile (I know there is an API, this is just for fun)... I already create a similar script using mechanize, and it works!

What's wrong with my code? Thanks

2
  • what are you getting as the response? Commented Apr 21, 2013 at 7:40
  • it won't logged in, so its jump back to /session/new Commented Apr 21, 2013 at 7:45

1 Answer 1

3

If you look at login form hidden fields, you will find there authenticity_token, which is required. Also, your url was wrong.

Here is complete example:

import requests
from lxml.html import fromstring

with requests.Session() as c:
    url = 'https://mobile.twitter.com/session'
    response = c.get(url)

    html = fromstring(response.content)
    payload = dict(html.forms[0].fields)

    payload.update({
       'username': '<username>@gmail.com',
       'password': '<password>',
    })

    print payload

    c.post(url, data=payload)
    r = c.get('https://mobile.twitter.com/account')
    print '<username>' in r.content
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.