赞
踩
Selenium 本身不支持直接连接到一个已经打开的浏览器页面。Selenium 启动的浏览器实例是一个全新的会话,它与手动打开的浏览器页面是分开的。但是,有一些变通的方法可以实现类似的效果。
一种方法是通过附加代理连接到已经打开的浏览器。下面是如何实现这一目标的步骤。
找到chrome的安装位置,执行命令:
chrome.exe --remote-debugging-port=9222 --user-data-dir="C:\path\to\your\chrome\profile"
# --user-data-dir="C:\path\to\your\chrome\profile" 目录需要提前创建好
from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.by import By # 配置 ChromeDriver 的选项以连接到已经运行的 Chrome 实例 chrome_options = Options() chrome_options.add_experimental_option("debuggerAddress", "127.0.0.1:9222") # 获取当前脚本的目录 import os current_dir = os.path.dirname(os.path.abspath(__file__)) chrome_driver_path = os.path.join(current_dir, 'chromedriver') # 设置 ChromeDriver 的服务 service = Service(chrome_driver_path) # 启动 WebDriver 并连接到现有的 Chrome 实例 driver = webdriver.Chrome(service=service, options=chrome_options) # 现在你可以使用 Selenium 控制已经打开的 Chrome 实例 driver.get("https://www.baidu.com") # 打印网页标题 print(driver.title) # 关闭浏览器 driver.quit()
目录层级结构
|-chromedriver
└── subfolder/
└── your_script.py
chrome.exe --remote-debugging-port=9222 --user-data-dir="C:\path\to\your\chrome\profile"
确保 Chrome 的可执行文件路径正确,并指定一个用户数据目录,以便保留浏览器状态。
from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.chrome.options import Options # 配置 ChromeDriver 的选项以连接到已经运行的 Chrome 实例 chrome_options = Options() chrome_options.add_experimental_option("debuggerAddress", "127.0.0.1:9222") # 获取当前脚本的目录 import os current_dir = os.path.dirname(os.path.abspath(__file__)) chrome_driver_path = os.path.join(current_dir, 'chromedriver') # 设置 ChromeDriver 的服务 service = Service(chrome_driver_path) # 启动 WebDriver 并连接到现有的 Chrome 实例 driver = webdriver.Chrome(service=service, options=chrome_options) # 现在你可以使用 Selenium 控制已经打开的 Chrome 实例 driver.get("https://www.baidu.com/") # 打印网页标题 print(driver.title) # 保持浏览器打开,等待用户手动关闭 input("Press Enter to close the browser...") # 关闭浏览器 driver.quit()
启动 Chrome 浏览器:
chrome.exe --remote-debugging-port=9222 --user-data-dir="C:\path\to\your\chrome\profile"
--remote-debugging-port=9222
:指定 Chrome 浏览器的远程调试端口。--user-data-dir="C:\path\to\your\chrome\profile"
:指定 Chrome 的用户数据目录。配置 ChromeDriver 的选项:
chrome_options.add_experimental_option("debuggerAddress", "127.0.0.1:9222")
127.0.0.1:9222
连接到已经运行的 Chrome 实例。启动 WebDriver 并连接到现有的 Chrome 实例:
driver = webdriver.Chrome(service=service, options=chrome_options)
通过这种方式,你可以让 Selenium 控制一个已经打开的 Chrome 浏览器实例,从而在现有会话中执行自动化任务。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。