Problem with programmatic login using httplib2

1.1k Views Asked by At

Im using httplib2 library in python to do a programmatic login to a website. Below is my code:

import urllib,httplib2
url='http://somesite.com'
header_data={'Content-type': 'application/x-www-form-urlencoded',
    'User-Agent':'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.10) Gecko/20100922 Ubuntu/10.10 (maverick) Firefox/3.6.10'
}
body={'username':'<username>','password':'<password>','Submit':'Sign in'}
http = httplib2.Http()
try:
    response,content = http.request(url,'POST',headers=header_data,body=urllib.urlencode(body)) 
except:
    print False
print response
print content

I get the dictionary in response, but the content variable is empty. It should have the html of the page,isnt it ?.

Any to fix this? Please Help Thank You.

1

There are 1 best solutions below

0
On

How about this?

from urllib import urlencode
from ulrlib2 import Request, urlopen

url='http://somesite.com'
header_data={'Content-type': 'application/x-www-form-urlencoded',
    'User-Agent':'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.10) Gecko/20100922 Ubuntu/10.10 (maverick) Firefox/3.6.10'}
body={'username':'<username>','password':'<password>','Submit':'Sign in'}

data = urlencode(body)
try:
    if method.upper() == 'GET':
        httpstream = urlopen(url+"&"+data)
    else:
        req = Request(url, data)
        httpstream = urlopen(req)
except:
    ...
result = httpstream.read()
httpstream.close()