如何使用 Python 登录网页并检索 cookie 以供以后使用? [英] How to use Python to login to a webpage and retrieve cookies for later usage?

查看:36
本文介绍了如何使用 Python 登录网页并检索 cookie 以供以后使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 python 下载和解析网页,但要访问它,我需要设置几个 cookie.因此,我需要先通过 https 登录到网页.登录时刻涉及向/login.php 发送两个 POST 参数(用户名、密码).在登录请求期间,我想从响应标头中检索 cookie 并存储它们,以便我可以在请求中使用它们来下载网页/data.php.

我将如何在 python(最好是 2.6)中做到这一点?如果可能,我只想使用内置模块.

解决方案

import urllib, urllib2, cookielib用户名 = '我的用户'密码 = '我的密码'cj = cookielib.CookieJar()开瓶器 = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))login_data = urllib.urlencode({'用户名':用户名,'j_password':密码})opener.open('http://www.example.com/login.php', login_data)resp = opener.open('http://www.example.com/hiddenpage.php')打印 resp.read()

resp.read() 是您要打开的页面的直接 html,您可以使用 opener 使用会话 cookie 查看任何页面.>

I want to download and parse webpage using python, but to access it I need a couple of cookies set. Therefore I need to login over https to the webpage first. The login moment involves sending two POST params (username, password) to /login.php. During the login request I want to retrieve the cookies from the response header and store them so I can use them in the request to download the webpage /data.php.

How would I do this in python (preferably 2.6)? If possible I only want to use builtin modules.

解决方案

import urllib, urllib2, cookielib

username = 'myuser'
password = 'mypassword'

cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
login_data = urllib.urlencode({'username' : username, 'j_password' : password})
opener.open('http://www.example.com/login.php', login_data)
resp = opener.open('http://www.example.com/hiddenpage.php')
print resp.read()

resp.read() is the straight html of the page you want to open, and you can use opener to view any page using your session cookie.

这篇关于如何使用 Python 登录网页并检索 cookie 以供以后使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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