使用python登录网站 [英] Login to website using python

查看:107
本文介绍了使用python登录网站的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Python登入这个网页

I am trying to login to this page using Python.

我尝试使用此其他Stack Overflow post ,并得到以下代码:

I tried using the steps described on this other Stack Overflow post, and got the following code:

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()

但是它给了我以下输出:

but that gave me the following output:

<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>

我做错了什么?

推荐答案

我建议使用美妙的 请求 模块。

I would recommend using the wonderful requests module.

以下代码将使您登录网站并在会话期间保留Cookie。

The code below will get you logged into the site and persist the cookies for the duration of the session.

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()

这篇关于使用python登录网站的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆