我在python中使用httplib2库来进行网站的程序化登录。以下是我的代码:
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
我收到字典作为回应,但内容变量为空。它应该有页面的html,不是吗?。
要解决这个问题吗? 请帮忙 谢谢。
答案 0 :(得分:0)
这个怎么样?
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()