2 python browser mechanize 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)
Run Code Online (Sandbox Code Playgroud)
我可以登录并将经过身份验证的页面转储到标准输出,或者在不识别 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')
Run Code Online (Sandbox Code Playgroud)