如何使用Python登录到一个网页,检索以后使用饼干? [英] How to use Python to login to a webpage and retrieve cookies for later usage?
问题描述
我想下载和使用python解析网页,但访问它,我需要一对夫妇上设置的Cookie。因此,我需要到https登录先转移到网页。登录一刻涉及发送两个POST PARAMS(用户名,密码),以/login.php。在登录请求我想要检索的响应头的饼干,并将它们存储这样我就可以用它们在请求下载网页/data.php。
我怎么会在Python做到这一点(preferably 2.6)?如果可能的话我只想使用内置模块。
进口的urllib,urllib2的,cookielib用户名='为myuser
密码='输入mypasswordCJ = cookielib.CookieJar()
首战= urllib2.build_opener(urllib2.HTTPCookieProcessor(CJ))
login_data = urllib.urlen code({用户名:用户名,'为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,你可以使用揭幕战
使用会话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登录到一个网页,检索以后使用饼干?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!