使用python登录网站

iom*_*tin 17 python cookies login

我正在尝试使用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()
Run Code Online (Sandbox Code Playgroud)

但这给了我以下输出:

<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>
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

Aco*_*orn 35

我建议使用精彩的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()
Run Code Online (Sandbox Code Playgroud)