通过selenium实现免登录

为啥要用 selenium, 因为单位的登录方式是使用 openid 登录的,我还不知道怎么去实现openid 登录,主要是没有文档。但是我希望通过脚本的方式登录去做一些自动化的工作。于是想到了通过selenium 模拟浏览器登录后获取cookie 然后调用 request 接口来实现一些自动化的操作。

安装

pip3 install selenium

实现登录

def do_login(username,password):
  options=webdriver.ChromeOptions()
  options.add_argument("--headless")  # 不打开浏览器页面
  driver = webdriver.Chrome(options=options)     # 打开 Chrome 浏览器
  driver.get("http://xxxxxx.com/login.html#/")
  driver.find_element_by_link_text(u"OpenId登录").click()
  driver.find_element_by_id("username").send_keys(username)
  driver.find_element_by_id("password").send_keys(password)
  driver.find_element_by_xpath(
      u"(.//*[normalize-space(text()) and normalize-space(.)='记住本次登录'])[2]/following::button[1]").click()
  cookies = driver.get_cookies() # 获取cookie
  driver.close()
  return cookies    

拿到cookie 之后,把cookie 值加到 request 请求的 cookie 字段就可以实现模拟登录进行一系列操作了。

     cookies = do_login("xxx", "xxxxx") # 输入登录账户密码
requests_session = requests.Session()
for cookie in cookies:
    requests_session.cookies.set(cookie['name'], cookie['value'])

然后通过 requests_session进行get 或post 等请求即可。

注意

注意 selenium 需要配合 chromedriver(调用Chrome浏览器) 或geckodriver(调用火狐浏览器),并且有版本兼容问题,

例如最新版本的Chrome浏览器是Chrome 71 其chromedriver 版本为 2.45.615355 具体参考 http://chromedriver.chromium.org/