kholidfu
kholidfu

Reputation: 74

How to use python requests with HTTPS

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

Upvotes: 1

Views: 1341

Answers (1)

gatto
gatto

Reputation: 2957

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

Upvotes: 3

Related Questions