Selenium遇ElementClickInterceptedException,如何结合ActionChains解决?
港交所网站Excel下载代码修复方案
问题说明
之前正常运行的港交所网页Excel下载代码,因网页更新后出现报错:
selenium.common.exceptions.ElementClickInterceptedException: Message: Element is not clickable at point (1250,464) because another element obscures it
原代码如下:
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 geckodriver = '/opt/geckodriver' options = webdriver.FirefoxOptions() options.add_argument('-headless') driver = webdriver.Firefox(executable_path=geckodriver, firefox_options=options) driver.get('https://www.hkex.com.hk/Market-Data/Futures-and-Options-Prices/Equity-Index/Hang-Seng-Index-Futures-and-Options?sc_lang=en#&product=HSI') WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, 'ete'))).click() time.sleep(2) html = driver.page_source print(html)
修复方案
报错原因是目标元素被其他页面元素遮挡,无法直接点击。可以将WebDriverWait等待元素的逻辑和ActionChains结合,先等待元素可点击,再通过动作链移动到元素位置后点击,避免遮挡问题。
修改后的完整代码
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 from selenium.webdriver.common.action_chains import ActionChains import time # 补上原代码缺失的导入 geckodriver = '/opt/geckodriver' options = webdriver.FirefoxOptions() options.add_argument('-headless') driver = webdriver.Firefox(executable_path=geckodriver, firefox_options=options) driver.get('https://www.hkex.com.hk/Market-Data/Futures-and-Options-Prices/Equity-Index/Hang-Seng-Index-Futures-and-Options?sc_lang=en#&product=HSI') # 先等待元素可点击,获取元素对象 target_element = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, 'ete'))) # 使用ActionChains移动到元素并点击 ActionChains(driver).move_to_element(target_element).click().perform() time.sleep(2) html = driver.page_source print(html)
关键修改点
- 导入
ActionChains模块和缺失的time模块 - 先通过
WebDriverWait获取到目标元素对象,再传入ActionChains执行点击操作,确保元素处于可交互状态后再通过动作链触发点击
内容的提问来源于stack exchange,提问作者idiot one
相关产品推荐
相关产品推荐

