簡體   English   中英

使用python登錄網站

[英]Login to website using python

我正在嘗試使用Python登錄此頁面

我嘗試使用此其他Stack Overflow帖子中描述的步驟,並獲得以下代碼:

import urllib, urllib2, cookielib

username = 'username'
password = 'password'

cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
login_data = urllib.urlencode({'username' : username, 'j_password' : password})
opener.open('http://friends.cisv.org/index.cfm', login_data)
resp = opener.open('http://friends.cisv.org/index.cfm?fuseaction=activities.list')
print resp.read()

但這給了我以下輸出:

<SCRIPT LANGUAGE="JavaScript">
    alert('Sorry.  You need to log back in to continue. You will be returned to the home page when you click on OK.');
    document.location.href='index.cfm';
</SCRIPT>

我究竟做錯了什么?

我建議使用精彩的requests模塊。

下面的代碼將讓您登錄該站點並在會話期間保留cookie。

import requests
import sys

EMAIL = ''
PASSWORD = ''

URL = 'http://friends.cisv.org'

def main():
    # Start a session so we can have persistant cookies
    session = requests.session(config={'verbose': sys.stderr})

    # This is the form data that the page sends when logging in
    login_data = {
        'loginemail': EMAIL,
        'loginpswd': PASSWORD,
        'submit': 'login',
    }

    # Authenticate
    r = session.post(URL, data=login_data)

    # Try accessing a page that requires you to be logged in
    r = session.get('http://friends.cisv.org/index.cfm?fuseaction=user.fullprofile')

if __name__ == '__main__':
    main()

遺憾的是,“登錄”一詞非常模糊。 這里給出的代碼顯然試圖使用HTTP基本身份驗證登錄。 我猜賭這個網站希望你以某種POST格式發送用戶名和密碼(這就是大多數基於網絡的登錄表單的工作方式)。 在這種情況下,您需要發送正確的POST請求,並保留它發送給您的任何cookie以備將來請求。 不幸的是我不知道這會是什么,這取決於網站。 您需要弄清楚它通常如何記錄用戶並嘗試遵循該模式。

暫無
暫無

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

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