Selenium点击SVG元素问题:无法点击path下载Excel文件
问题解决:Selenium点击SVG元素下载Excel文件
问题背景
需要编写Python Selenium代码,点击包含svg、id、g、path标签的path元素来下载Excel文件,但当前代码无法实现点击操作:页面滚动无效,必须点击绿色“Portfolio”按钮定位到目标区域后才能完成下载。
问题分析
- 直接使用
window.scrollTo滚动无效,可能是页面采用动态布局或该区域需要通过点击Portfolio按钮触发加载/显示 - 原XPATH定位过于冗长,可能匹配到多个元素或未定位到正确的可点击元素
- 未先触发Portfolio按钮的点击操作,导致目标下载元素处于不可见或未激活状态
修正后的代码
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 from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.action_chains import ActionChains import time # 配置Chrome选项 chrome_options = Options() chrome_options.add_argument("--no-sandbox") chrome_options.add_argument('disable-notifications') chrome_options.add_argument("window-size=1280,720") # 初始化驱动 webdriver_service = Service("chromedriver/chromedriver") # 替换为你的chromedriver路径 driver = webdriver.Chrome(service=webdriver_service, options=chrome_options) wait = WebDriverWait(driver, 25) try: driver.get('https://www.edelweissmf.com/types-of-mutual-funds/bharat-bond-funds/edelweiss-etf-bharat-bond-2023') # 先点击绿色的Portfolio按钮,定位到目标区域 portfolio_btn = wait.until(EC.element_to_be_clickable((By.XPATH, "//button[contains(text(), 'Portfolio')]"))) portfolio_btn.click() time.sleep(1) # 等待页面切换/加载 # 定位下载Excel的SVG元素(简化XPATH,直接定位可点击的path或父级svg) download_element = wait.until(EC.visibility_of_element_located((By.XPATH, "//*[@id='Capa_1']//*[name()='path']"))) # 使用ActionChains确保点击生效(避免元素不可点击的问题) ActionChains(driver).move_to_element(download_element).click().perform() finally: # 可根据需求调整是否关闭浏览器,若需等待下载完成可延长时间 time.sleep(5) driver.quit()
关键修改说明
- 增加了点击Portfolio按钮的步骤,确保目标区域被激活并可见
- 简化了XPATH定位,直接通过SVG的id定位内部path元素,减少匹配误差
- 使用
ActionChains的move_to_element+click操作,避免因元素不在视口或覆盖导致的点击失败 - 增加了
try-finally块,确保浏览器能正常关闭 - 移除了无关的pandas和BeautifulSoup导入(若后续需要处理下载的Excel可保留)
内容的提问来源于stack exchange,提问作者New_Coder
相关产品推荐
相关产品推荐

