首页 > 解决方案 > 使用 Selenium 登录 Gmail/保存 cookie,然后使用请求

问题描述

我正在尝试使用 Selenium 登录 Gmail,然后使用请求(或 aiohttp)进行 Google 搜索。

在这之前,我使用纯 Selenium 登录并进行搜索、观看 YouTube 等。但最近我开始询问是否可以使用纯请求登录 Gmail。有人告诉我,由于使用了大量的 JavaScript,这非常困难。于是想到了一个新的方式(使用Selenium登录,然后继续使用requests),想看看能不能用。

driver = webdriver.Chrome()
driver.get("https://accounts.google.com/signin")
email_phone = driver.find_element_by_xpath("//input[@id='identifierId']")
email_phone.send_keys("your_emailid_phone")
driver.find_element_by_id("identifierNext").click()
password = WebDriverWait(driver, 5).until(
EC.element_to_be_clickable((By.XPATH, "//input[@name='password']")))
password.send_keys("your_password")
driver.find_element_by_id("passwordNext").click()

time.sleep(5)
driver.get("https://google.com")
pickle.dump( driver.get_cookies() , open("cookies.pkl","wb"))



session = requests.session()
with open('cookies.pkl', 'rb') as f:
    session.cookies.update(pickle.load(f))
    session.get("https://youtube.com") 

运行此代码时没有错误。但是,我担心这种方法是否可行。如果我加载登录 Gmail(使用 Selenium)时存在的 cookie,我所做的任何活动都会反映在我的 Gmail 上(我的意图)。

标签: pythonpython-3.xseleniumbeautifulsouppython-requests

解决方案


如果你坚持使用selenium,那么你应该知道

  1. password不应该WebDriverWait(driver, ...WebDriverWait(driver, ...在这种情况下,不会返回任何对您有用的东西。当在时限内找不到特定元素时也会引发错误。
  2. 您必须一起保存cookie和过期,以便在您真正需要时再次获得新的
  3. 小心域名问题。在您的情况下,您最终访问了 Google 主站点,这意味着如果您driver.get_cookies()在此之后使用,您将无法获取属于https://myaccount.google.com/

完整代码

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
import pickle

def save_cookies():
    email = "@gmail.com"
    password = ""

    driver = webdriver.Chrome()
    driver.get("https://accounts.google.com/signin")
    email_phone = driver.find_element_by_xpath("//input[@id='identifierId']")
    email_phone.send_keys(email)
    driver.find_element_by_id("identifierNext").click()
    WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.XPATH, "//input[@name='password']")))
    password = driver.find_element_by_xpath("//input[@name='password']")
    password.send_keys(password)
    driver.find_element_by_id("passwordNext").click()
    time.sleep(5)

    google_cookies = driver.get_cookies()
    cookies = ({cookie.get("name"):cookie.get("value") for cookie in google_cookies}, google_cookies[0].get("expiry"))

    with open("cookies.pkl","wb") as fd:
        pickle.dump(cookies, fd)

    return cookies


import requests

with requests.Session() as s:
    with open("cookies.pkl","rb") as fd:
        cookies, expiry = pickle.load(fd)
        if expiry < time.time():
            cookies, expiry = save_cookies()
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
        "Referer": "https://www.google.com/",
        "Accept-Encoding": "deflate",
        "Accept-Language": "en;q=0.6",
        }

    resp = s.get("https://myaccount.google.com/"
        ,headers=headers,cookies=cookies)
    print(resp.url)

推荐阅读