使用 Selenium 自动打开 Chrome 浏览器并连接调试端口
import os
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
# 检查是否已经有浏览器打开
def check_browser():
try:
response = os.popen('netstat -ano | findstr "9527"').read()
if response:
return True
else:
return False
except Exception as e:
print(e)
return False
# 使用CMD命令打开一个新的浏览器
if __name__ == '__main__':
if not check_browser():
os.system(r'start chrome --remote-debugging-port=9527 --user-data-dir='D:\评阅用'')
# 获取刚才打开的浏览器
options = Options()
options.add_experimental_option('debuggerAddress', '127.0.0.1:9527')
browser = webdriver.Chrome(options=options)
browser.get('https://menhu.pt.ouchn.cn/site/ouchnPc/index')
print(browser.title)
代码功能:
- 检查浏览器是否已打开: 使用
netstat命令检查端口 9527 是否被占用,如果被占用,则认为浏览器已打开。 - 打开新的浏览器: 如果浏览器未打开,则使用
os.system命令打开新的 Chrome 浏览器,并指定远程调试端口为 9527 和用户数据目录为 'D:\评阅用'。 - 连接到调试端口: 使用 Selenium 的
Options类设置调试地址为 '127.0.0.1:9527',然后创建 ChromeDriver 实例,并访问目标网页。
使用说明:
- 请确保您的系统上已安装 Chrome 浏览器和 Selenium 库。
- 将代码中的用户数据目录路径修改为您自己的目录。
- 运行代码后,您可以使用浏览器调试工具进行网页调试。
原文地址: https://www.cveoy.top/t/topic/oAR5 著作权归作者所有。请勿转载和采集!