编程语言
首页 > 编程语言> > Python使用webbrowser,urllib和CookieJar验证并启动私有页面

Python使用webbrowser,urllib和CookieJar验证并启动私有页面

作者:互联网

我想使用cookiejar登录,并且不启动登录页面,而是启用经过身份验证后才能看到的页面.我知道机械化这样做但除了现在不为我工作之外,我宁愿这样做也没有它.我现在有,

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)

我要么能够登录并将经过身份验证的页面转储到stdout,要么在不识别cookie的情况下启动登录页面,但我无法在登录后启动我想要的页面.帮助赞赏.

解决方法:

您可以使用selenium模块执行此操作.它启动一个浏览器(chrome,Firefox,IE等),其中加载了一个扩展程序,允许您控制浏览器.

以下是将cookie加载到其中的方法:

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

标签:python,urllib,browser,mechanize,cookiejar
来源: https://codeday.me/bug/20191003/1847279.html