硒和谷歌-您如何使用Cookie? [英] Selenium and Google - How do you use cookies?

查看:106
本文介绍了硒和谷歌-您如何使用Cookie?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用Selenium on Adwords构建报告工具. (不,我不能使用Google的API,因为它不提供我想要的功能).

I am currently building a reporting tool with Selenium on Adwords. (And no, I cannot use Google's API because it doesn't provide the functionality I want).

我试图避免登录和注销,因为我知道频繁的登录和注销不如基于cookie的身份验证方便.

I am trying to avoid logging in and logging out, because I understand frequent logins and logouts are not as convenient as cookie based authentication.

我有以下代码:save.py

I have the following code: save.py

try:
  driver = webdriver.Chrome()
  driver.get('https://adwords.google.com')
  time.sleep(90)
  # Manually login to adwords page and wait
  pickle.dump( driver.get_cookies() , open("cookies.pkl","wb"))

finally:
  driver.close()

这是:load.py

And this: load.py

try:
  driver = webdriver.Chrome()
  cookies = pickle.load(open("cookies.pkl", "rb"))
  for cookie in cookies:
    driver.add_cookie(cookie)

  driver.get('https://adwords.google.com/')
  time.sleep(60)

finally:
  driver.close()

当我第一次运行load.py时,实际上我可以看到在登录到Adwords时显示的微调框.但是不久之后,我就注销了!

When I first run load.py, I am actually able to see the spinner that shows up when one logs into Adwords. Shortly after however, I get logged out!

我不知道是什么原因导致Google的身份验证系统注销了我.您认为是什么原因造成的?

I don't know what is causing Google's authentication system to log me out. What do you think is the cause of this?

代码回购: https://gist.github.com/anonymous/63d32e49f59a09ab82fac1f9f972d555 /p>

推荐答案

方法driver.add_cookie仅适用于当前域.因此,在调用driver.add_cookie之前,您首先必须使用driver.get(...)设置域:

The method driver.add_cookie works for the current domain only. So you'll first have to set the domain with driver.get(...) before calling driver.add_cookie:

import json, re

def save_cookies(driver, file_path):
  with open(file_path, 'w') as file:
    cfg = {
      'url': driver.current_url,
      'cookies': driver.get_cookies()
    }
    json.dump(cfg, file, indent=2)

def load_cookies(driver, file_path):
  with open(file_path, 'r') as file :
    cfg = json.load(file)
    driver.get(re.match(".+?//[^/]+", cfg['url'])[0] + '/favicon.ico')

    for cookie in cfg['cookies']:
      cookie['expiry'] = cookie.get('expiry', -1)
      driver.add_cookie(cookie);

# save the cookies
save_cookies(driver, r"cookies.json");

# restore cookies
load_cookies(driver, r"cookies.json")

或通过调用devtool API来保存/恢复所有域的cookie(仅适用于Chrome):

Or by calling the devtool API to save/restore the cookies for all the domains (Chrome only):

from selenium import webdriver
import json, base64

def send_devtools(driver, cmd, params={}):
  resource = "/session/%s/chromium/send_command_and_get_result" % driver.session_id
  url = driver.command_executor._url + resource
  body = json.dumps({'cmd': cmd, 'params': params})
  response = driver.command_executor._request('POST', url, body)
  if response['status']:
    raise Exception(response.get('value'))
  return response.get('value')

def save_cookies(driver, file_path):
  cookies = send_devtools(driver, "Network.getAllCookies", {})  
  with open(file_path, 'w') as file:
    json.dump(cookies, file, indent=2)

def load_cookies(driver, file_path):
  with open(file_path, 'r') as file :
    cookies = json.load(file)
    send_devtools(driver, "Network.setCookies", cookies)

# save cookies
save_cookies(driver, r"c:\temp\cookies.json");

# restore cookies
load_cookies(driver, r"c:\temp\cookies.json")

这篇关于硒和谷歌-您如何使用Cookie?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆