如何用Python Selenium点击含onclick属性的<tr>标签?解决滚动报错
问题描述
目标HTML代码片段:
<table .... > <tbody .... > <tr style="cursor:hand" onclick="OpenSession ("xxxx", "yyyyy", "zzzz")"> ... </tr> <tr style="cursor:hand" onclick="OpenSession ("aaaa", "bbbbb", "cccc")"> ... </tr> </tbody> </table>
尝试用Python Selenium点击带有onclick属性的<tr>标签,编写的代码:
tr_elements = driver.find_elements(By.TAG_NAME,value='tr') for tr in tr_elements: if tr.get_attribute('onclick'): print(tr) WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//tr[contains(@onclick, 'OpenSession ')]"))).click() time.sleep(5)
运行时出现错误:
<selenium.webdriver.remote.webelement.WebElement (session="96f27c0a-2870-4011-8668-abbbdab5bd2c", element="7a4f8c92-f571-471e-ad63-6c6113f17494")>
selenium.common.exceptions.ElementNotInteractableException: Message: Element could not be scrolled into view
解决方案
核心问题分析
原代码存在两个关键问题:
- 循环中每次通过固定XPATH定位元素,导致每次点击的都是第一个符合条件的
<tr>,而非当前循环的元素; - 未处理元素不在视口内、被遮挡的情况,触发
ElementNotInteractableException。
修正后的代码方案
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.webdriver.common.action_chains import ActionChains import time # 直接定位所有带OpenSession onclick事件的tr元素 target_trs = WebDriverWait(driver, 20).until( EC.presence_of_all_elements_located((By.XPATH, "//tr[contains(@onclick, 'OpenSession')]")) ) for tr in target_trs: try: # 方式1:用JavaScript滚动到元素中央,确保在视口内 driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", tr) # 等待元素可点击后点击 WebDriverWait(driver, 10).until(EC.element_to_be_clickable(tr)).click() # 方式2:用ActionChains模拟鼠标操作(自动处理滚动) # ActionChains(driver).move_to_element(tr).click().perform() # 方式3:直接用JS触发onclick,绕过可见性检查(适合元素被遮挡的场景) # driver.execute_script("arguments[0].click();", tr) # 替换time.sleep为显式等待更佳(比如等待新页面/元素加载完成) time.sleep(2) except Exception as e: print(f"点击元素失败: {str(e)}") continue
关键优化点
- 精准定位元素:直接通过XPATH筛选目标
<tr>,避免遍历所有无关元素; - 解决滚动问题:三种方式任选其一,确保元素进入视口或绕过可见性限制;
- 避免重复定位:循环中直接操作当前获取的元素,而非重复定位同一元素;
- 替换固定等待:尽量用显式等待(如
EC.url_changes()、EC.presence_of_element_located())替代time.sleep,提升稳定性。
内容的提问来源于stack exchange,提问作者Christophe C.
相关产品推荐
相关产品推荐

