selenium-常见问题解决方案汇总

发布于:2024-12-08 ⋅ 阅读:(180) ⋅ 点赞:(0)

selenium版本

selenium版本为: 3.141.0
注:selenium4x跟selenium3x会有不同的使用方法,

selenium代理本地浏览器页面

利用 Selenium 库实现对 Google Chrome 浏览器的自动化控制。

首先,通过 os.popen 命令启动本地 Chrome,并开启远程调试端口。接着,配置 ChromeDriver 的路径和浏览器选项,确保 Selenium 能够连接到已启动的 Chrome 实例。代码随后初始化 WebDriver,最大化浏览器窗口,并导航至指定页面。

import os
import time  # 事件库,用于硬性等待

from selenium import webdriver  # 导入selenium的webdriver模块

os.popen('start chrome --remote-debugging-port=9527 --user-data-dir="C:\selenium"')

chrome_driver_path = r"C:\Program Files\Google\Chrome\Application\chromedriver.exe"

options = webdriver.ChromeOptions()

options.binary_location = r"C:\Program Files\Google\Chrome\Application\chrome.exe"

options.add_experimental_option("debuggerAddress", "127.0.0.1:9527")
driver = webdriver.Chrome(executable_path=chrome_driver_path, options=options)
# 最大化浏览器窗口
driver.maximize_window()

url = "https://etax.guangdong.chinatax.gov.cn:8443/loginb/"
driver.get(url)

time.sleep(2)

Selenium之多窗口句柄的切换

在使用 Selenium 进行浏览器自动化操作时,常常需要处理多个浏览器窗口或标签页。例如,当点击一个 <a 标签的超链接时,可能会在新窗口或新标签页中打开目标页面。如果不进行窗口句柄的切换,Selenium 仍会在原窗口中执行操作,从而无法控制新打开的窗口。本文将介绍如何使用 Selenium 进行多窗口句柄的切换,确保能够顺利操作新窗口或标签页。

多窗口句柄的基本概念
每个浏览器窗口或标签页在 Selenium 中都有一个唯一的句柄(Handle)。通过获取所有窗口的句柄,开发者可以在不同窗口之间切换,执行相应的操作。以下是处理多窗口的基本步骤:

  • 获取当前所有窗口的句柄
  • 切换到目标窗口 执行所需操作
  • 切换回原窗口(如有需要)
# 获取当前页面的所有句柄
window_handles = driver.window_handles
# 切换到新的标签页(假设新标签页是 window_handles[1])
driver.switch_to.window(window_handles[1])
# 在新窗口中执行操作,例如获取页面标题
print("新窗口的标题:", driver.title)
# 切换回原来的标签页(首页)
driver.switch_to.window(window_handles[0])
# 在原窗口中继续操作
print("原窗口的标题:", driver.title)

注:driver的定义见前文


网站公告

今日签到

点亮在社区的每一天
去签到