2025年2月

selenium 截屏 设置带用户名密码的代理和注入cookie

今天想对一个metrics 数据做截屏自动保存, 想到使用 selenium 来做. 于是让 chatGPT 给写了一个脚本. 发现其中有2处需要注意的地方.

  1. 一般的设置代理方法(selenium.webdriver.common.proxy不包含代理的用户名密码)不管用, 必须使用 seleniumwire.
  2. 注入 cookie. 为什么不通过登录获得 cookie 而使用注入? 默认的登录使用 2FA, 其中需要MAC 的指纹, 所以很麻烦, 索性一开始先从浏览器拿一个cookie注入.

python 代码如下:

from selenium import webdriver
from seleniumwire import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.proxy import Proxy, ProxyType
from PIL import Image
import time

def init_chrome_driver():
    # 设置代理
    options = {
        'proxy': {
            'http': 'http://user:password@proxy.tianxiaohui.com:8080', 
            'https': 'http://user:password@proxy.tianxiaohui.com:8080',
            'no_proxy': 'localhost,127.0.0.1' # excludes
        }
    }

    # 设置Chrome选项
    chrome_options = Options()
    chrome_options.add_argument("--headless")  # 无头模式
    chrome_options.add_argument("--disable-gpu")
    chrome_options.add_argument("--window-size=1920x1080")

    # 设置Chrome驱动路径
    chrome_driver_path = '/Users/supra/work/tools/chromedriver-mac-x64/chromedriver'  # 请替换为你的chromedriver路径

    # 初始化Chrome驱动
    service = Service(chrome_driver_path)
    driver = webdriver.Chrome(service=service, options=chrome_options, seleniumwire_options=options)

    return driver

def setup_driver(driver):
    # 打开一个空白页
    driver.get('http://mydash.tianxiaohui.com/?orgId=1')
    # 等待页面加载完成
    time.sleep(5)

    # 添加现有的cookie
    cookies = [
        {
            'name': 'grafana_session',
            'value': '5c74f90284d363050b63c20c86a2d336',
            'path': '/',
            'domain': 'mydash.tianxiaohui.com'
        }
    ]

    for cookie in cookies:
        driver.add_cookie(cookie)

    return driver

def take_screenshot(driver, url, screenshot_abs_file):
    # 打开网址
    driver.get(url)
    # 等待页面加载完成
    time.sleep(30)
    # 截图并保存到本地
    driver.save_screenshot(screenshot_abs_file)

    return driver

driver = init_chrome_driver()
driver = setup_driver(driver)
url = 'http://mydash.tianxiaohui.com/d/test_dash'
print(url)
screenshot_path = f'/Users/supra/Downloads/screenshot.png'
driver = take_screenshot(driver, url, screenshot_path)

# 关闭浏览器
driver.quit()

# 使用Pillow库打开截图并显示
#image = Image.open(screenshot_path)
#image.show()