使用python登录网站需要帮助吗

2024-10-01 04:57:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要抓取一些大学项目的网站,我已经到了一个需要登录的网站的死胡同。我使用Python中的urllib、urllib2、cookielib模块登录。它不适用于http://www.cafemom.com。 我收到的http响应保存在一个.txt文件中,并对应于“登录不成功”页面。在

我也尝试过使用“twill”软件包来实现这个目的,但我也没有成功。有人能建议我该怎么做吗?在

下面是我为此目的使用的main 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()

我也尝试过使用这个代码,但没有成功

^{pr2}$

Tags: debugselfhttpemaildefwwwpasswordopener
1条回答
网友
1楼 · 发布于 2024-10-01 04:57:17

我不确定这是否正是你所需要的,但它值得试试看。那个python优秀的requests模块同时支持cookies和HTTP基本身份验证。在

这些示例直接来自其文档。在

下面是一个基本的auth示例

payload = {'identifer': email, 'password': password}
r = requests.post("http://www.cafemom.com/login.php?", data=payload)

下面是如何传递以前保存的cookies(您可以通过“r.cookies”从以前的请求访问它)。在

^{pr2}$

以下是如何阅读您的请求的回复

f = open("responseCafemom.txt","w")
f.write(r.text)

相关问题 更多 >