
在使用Selenium进行Web自动化测试或数据抓取时,开发者常会遇到各种元素定位与交互的难题。其中,处理页面加载初期出现的弹窗(如Cookie同意框)以及与SVG(Scalable Vector Graphics)元素交互是两个常见的挑战。本教程将深入分析这些问题,并提供一套行之有效的解决方案。
原始代码在尝试点击SVG元素时遇到了TimeoutException,这通常意味着Selenium在指定时间内未能找到或未能与目标元素进行交互。导致此问题的原因可能有两个主要方面:
为了成功实现对目标网站的自动化操作,我们需要按照正确的顺序解决上述问题。
在访问目标URL后,通常会立即出现一个Cookie同意弹窗。在进行任何其他操作之前,必须先点击该弹窗的“同意”按钮以关闭它。
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
# Setup the WebDriver
driver = webdriver.Firefox()
# Open the page
driver.get("https://www.investing.com/equities/tencent-holdings-hk-historical-data")
# 等待并点击Cookie同意按钮
try:
cookie_accept_button = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, "//*[@id='onetrust-accept-btn-handler']"))
)
cookie_accept_button.click()
print("成功点击Cookie同意按钮。")
except Exception as e:
print(f"未找到或无法点击Cookie同意按钮,可能已被处理或不存在: {e}")
解释: 我们使用WebDriverWait配合EC.element_to_be_clickable来等待并确保Cookie同意按钮(通过其ID onetrust-accept-btn-handler定位)是可点击的,然后执行点击操作。这确保了后续操作不会被弹窗阻碍。
原始的XPath //*[@id='__next']/div[2]/div[2]/div[2]/div[1]/div[2]/div[2]/div[2]/div[2]/span/svg/g/path在定位SVG内部元素时失败,这是因为SVG元素及其内部标签(如<g>和<path>)属于SVG命名空间,而非HTML命名空间。为了正确匹配这些元素,我们需要在XPath中使用local-name()函数。
local-name()函数会返回元素的本地名称,忽略其命名空间前缀。这使得我们可以在不关心命名空间的情况下匹配元素。
# 等待并点击SVG元素(日期选择器图标)
# 使用local-name()函数处理SVG命名空间问题
svg_element_xpath = "//*[@id='__next']/div[2]/div[2]/div[2]/div[1]/div[2]/div[2]/div[2]/div[2]/span/*[local-name()='svg']/*[local-name()='g']/*[local-name()='path']"
svg_element = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, svg_element_xpath))
)
svg_element.click()
print("成功点击SVG日期选择器图标。")解释: 通过将svg、g和path替换为*[local-name()='svg']、*[local-name()='g']和*[local-name()='path'],我们能够准确地定位到SVG内部的路径元素,从而成功触发日期选择器。
点击SVG图标后,一个日期输入框会变得可见。我们可以通过其type='date'属性来定位它,并使用clear()和send_keys()方法来设置日期。
# 找到日期输入框,清空并设置新值
date_input = WebDriverWait(driver, 10).until(
EC.visibility_of_element_located((By.CSS_SELECTOR, "input[type='date']"))
)
date_input.clear()
date_input.send_keys("2020-01-01")
print("成功输入日期值:2020-01-01。")解释: EC.visibility_of_element_located确保日期输入框在操作前是可见的。clear()方法用于清除输入框中可能存在的默认值,send_keys()则用于输入新的日期。
在输入日期后,通常需要点击一个“Apply”或“应用”按钮来确认更改。
# 找到并点击“Apply”按钮
apply_button = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, "//button[text()='Apply']"))
)
apply_button.click()
print("成功点击“Apply”按钮。")解释: 这里使用XPath //button[text()='Apply']来定位文本内容为“Apply”的按钮。同样,EC.element_to_be_clickable确保按钮在点击前是可交互的。
将上述所有步骤整合,构成一个完整的、健壮的Selenium自动化脚本:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
# Setup the WebDriver
# 建议使用WebDriverManager等工具管理驱动,或确保驱动已正确配置到PATH
driver = webdriver.Firefox()
driver.maximize_window() # 最大化窗口,有时有助于元素可见性
# Open the page
driver.get("https://www.investing.com/equities/tencent-holdings-hk-historical-data")
try:
# 1. 等待并点击Cookie同意按钮
print("尝试处理Cookie同意弹窗...")
cookie_accept_button = WebDriverWait(driver, 15).until( # 增加等待时间,确保弹窗出现
EC.element_to_be_clickable((By.XPATH, "//*[@id='onetrust-accept-btn-handler']"))
)
cookie_accept_button.click()
print("成功点击Cookie同意按钮。")
time.sleep(1) # 短暂等待页面更新
except Exception as e:
print(f"未找到或无法点击Cookie同意按钮,可能已被处理或不存在: {e}")
try:
# 2. 等待并点击SVG元素(日期选择器图标)
print("尝试点击SVG日期选择器图标...")
svg_element_xpath = "//*[@id='__next']/div[2]/div[2]/div[2]/div[1]/div[2]/div[2]/div[2]/div[2]/span/*[local-name()='svg']/*[local-name()='g']/*[local-name()='path']"
svg_element = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, svg_element_xpath))
)
svg_element.click()
print("成功点击SVG日期选择器图标。")
time.sleep(1) # 短暂等待日期选择器弹出
except Exception as e:
print(f"点击SVG日期选择器图标失败: {e}")
driver.quit()
exit()
try:
# 3. 找到日期输入框,清空并设置新值
print("尝试输入日期值...")
date_input = WebDriverWait(driver, 10).until(
EC.visibility_of_element_located((By.CSS_SELECTOR, "input[type='date']"))
)
date_input.clear()
date_input.send_keys("2020-01-01")
print("成功输入日期值:2020-01-01。")
time.sleep(1) # 短暂等待输入框更新
except Exception as e:
print(f"输入日期值失败: {e}")
driver.quit()
exit()
try:
# 4. 找到并点击“Apply”按钮
print("尝试点击“Apply”按钮...")
apply_button = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, "//button[text()='Apply']"))
)
apply_button.click()
print("成功点击“Apply”按钮。")
time.sleep(3) # 留出时间等待页面数据加载
except Exception as e:
print(f"点击“Apply”按钮失败: {e}")
driver.quit()
exit()
# 5. 打印页面源代码
print("\n--- 页面源代码 ---")
page_source = driver.page_source.encode('utf-8').decode('utf-8')
print(page_source[:2000]) # 仅打印前2000字符,避免输出过长
# 确保关闭浏览器
driver.quit()
print("\n自动化流程完成,浏览器已关闭。")from selenium.webdriver.firefox.options import Options
options = Options()
options.add_argument("--headless")
driver = webdriver.Firefox(options=options)通过遵循这些策略,可以显著提高Selenium自动化脚本的稳定性、可靠性和维护性,有效应对各种复杂的Web交互场景。
以上就是Selenium自动化Web交互:处理SVG元素与日期输入框的策略的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号