Python selenium使用自定义userdata

# -*- coding: utf-8 -*-
import os
import pathlib
from time import sleep

from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.chrome.options import Options
from webdriver_manager.chrome import ChromeDriverManager

# 检查当前目录是否存在Chrome WebDriver文件
webdriver_path = "./chromedriver"
if not os.path.exists(webdriver_path):
    # 如果不存在,自动下载适合你Chrome版本的WebDriver
    webdriver_path = ChromeDriverManager().install()

# 创建Chrome WebDriver服务
service = ChromeService(executable_path=webdriver_path)

# 创建Chrome浏览器选项
chrome_options = Options()

scriptDirectory = pathlib.Path().absolute()
chrome_options.add_argument(f"user-data-dir={scriptDirectory}\\sjfn_data")  # 实际脚本的目录下的userdata

# 启用本地存储空间
chrome_options.add_argument("--enable-local-storage")

# 创建Chrome浏览器实例并传入选项
driver = webdriver.Chrome(service=service, options=chrome_options)

# 打开网站
driver.get("https://www.sjfn.com")

# 等待

sleep(10)

# 关闭浏览器
driver.quit()

Sitemap · Rss

津ICP备2021004480号-3