我需要为一个大学项目爬取几个网站,而对于一个需要登录的网站,我已经走到了死胡同。我正在使用 Python 中的 urllib、urllib2、cookielib 模块登录。它不适用于http://www.cafemom.com。我收到的 http 响应保存在 .txt 文件中,并对应于“登录失败”页面。
为此,我还尝试使用“twill”包,但这对我来说也不起作用。谁能建议我应该怎么做?
下面是我用于此目的的主要 login() 方法。
def urlopen(req):
try:
r = urllib2.urlopen(req)
except IOError, e:
if hasattr(e, 'code'):
print 'The server couldn\'t fulfill the request.'
print 'Error code: ', e.code
elif hasattr(e, 'reason'):
print 'We failed to reach a server.'
print 'Reason: ', e.reason
raise
return r
class Cafemom:
"""Communication with Cafemom"""
def __init__(self, cookieFile = 'cookie.jar', debug = 0):
self.cookieFile = cookieFile
self.debug = debug
self.loggedIn = 0
self.uid = ''
self.email = ''
self.passwd = ''
self.cj = cookielib.LWPCookieJar()
if os.path.isfile(cookieFile):
self.cj.load(cookieFile)
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cj))
urllib2.install_opener(opener)
def __del__(self):
self.cj.save(self.cookieFile)
def login(self, email, password):
"""Logging in Cafemom"""
self.email = email
self.passwd = password
url='http://www.cafemom.com/lohin.php?'
cnt='http://www.cafemom.com'
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
body = {'identifier': email, 'password': password }
if self.debug == 1:
print "Logging in..."
req = urllib2.Request(url, urllib.urlencode(body), headers)
print urllib.urlencode(body)
#print req.group()
handle = urlopen(req)
h = handle.read()
f = open("responseCafemom.txt","w")
f.write(f)
f.close()
我也尝试使用此代码但不成功
import urllib, urllib2, cookielib
username = myusername
password = mypassword
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
login_data = urllib.urlencode({'identifier' : username, 'password' : password})
opener.open('http://www.cafemom.com/login.php', login_data)
resp = opener.open('http://www.cafemom.com')
print resp.read()