簡體   English   中英

需要使用python登錄網站的幫助

[英]Need help logging in to a website using python

我需要抓取一些用於大學項目的網站,但是對於需要登錄的網站來說,我已經陷入僵局。 我使用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()

我不確定這是否正是您所需要的,但是值得一試.python的出色請求模塊支持cookie和HTTP基本身份驗證。

這些示例直接來自其文檔。

這是基本的身份驗證示例

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

這是傳遞先前保存的Cookie的方法(您可以使用“ r.cookies”從先前的請求中訪問。Cookie商店只是字典。

r = requests.get(url, cookies=cookies)

這是如何閱讀您的請求的響應

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM