使用webbrowser、urllib和CookieJar进行Python身份验证并打开私有页面

2 投票
2 回答
5927 浏览
提问于 2025-04-17 13:19

我想用cookiejar登录,并且直接打开一个只有在登录后才能看到的页面,而不是登录页面。我知道mechanize可以做到这一点,但现在对我来说不太好用,我更想不用它。现在我有了,

import urllib, urllib2, cookielib, webbrowser
from cookielib import CookieJar

username = 'my_username'
password = 'my_password'
url = 'my_login_page'

cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
login_data = urllib.urlencode({'my_username' : username, 'my_password' : password})
opener.open(url, login_data)
page_to_launch = 'my_authenticated_url'
webbrowser.open(page_to_launch, new=1, autoraise=1)

我要么能登录并把登录后的页面内容输出到屏幕上,要么能打开登录页面但不识别cookie,但我就是无法在登录后打开我想要的页面。希望能得到帮助。

2 个回答

1

你的 cookies 没有传到浏览器里。

webbrowser 这个库并没有处理你存储在 CookieJar 里的 cookies 的功能。它只是一个用来打开浏览器并访问网址的通用工具。你要么得自己实现一个可以把 cookies 存到浏览器里的 CookieJar(这绝对不是个简单的任务),要么就得找一个其他的库来帮你解决这个问题。

5

你可以使用selenium这个模块来实现这个功能。它会启动一个浏览器(比如Chrome、Firefox、IE等),并加载一个扩展,这样你就可以控制这个浏览器了。

下面是如何把cookies加载进去的方法:

from selenium import webdriver
driver = webdriver.Firefox() # open the browser

# Go to the correct domain
driver.get("http://www.example.com")

# Now set the cookie. Here's one for the entire domain
# the cookie name here is 'key' and it's value is 'value'
driver.add_cookie({'name':'key', 'value':'value', 'path':'/'})
# additional keys that can be passed in are:
# 'domain' -> String,
# 'secure' -> Boolean,
# 'expiry' -> Milliseconds since the Epoch it should expire.

# finally we visit the hidden page
driver.get('http://www.example.com/secret_page.html')

撰写回答