【问题标题】:How to click on python object contains onclick attribute in <tr> tag如何点击 python 对象在 <tr> 标签中包含 onclick 属性
【发布时间】:2023-02-09 06:05:24
【问题描述】:

我正在使用以下 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库,我想点击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:消息:无法将元素滚动到视图中

【问题讨论】:

    标签: python selenium


    【解决方案1】:

    好吧,如果你不给网站,那很难说。

    我猜该元素在页面中不可见。您可以首先尝试像这样最大化窗口和无头模式,在脚本的开头添加以下代码。

    from selenium import webdriver
    
    options = webdriver.ChromeOptions()
    
    options.add_argument("--headless")
    options.add_argument("--start-maximized")
    
    driver = webdriver.Chrome(options=options)
    

    【讨论】:

    • @anarchie:谢谢你的回复。为了不让帖子过载,我已经在我的 python 脚本中考虑了这些元素,因为它显示了我必须单击的元素
    • @ChristopheC。你能分享这个网站吗?
    • 不幸的是不是因为有很多机密信息
    • 你能试试这个吗driver.execute_script("arguments[0].scrollIntoView();", tr),在你的for循环之前添加它
    • 命令已执行,但仿真没有变化
    【解决方案2】:

    找出所有元素然后迭代的最佳方法。 当单击可单击元素时,页面将刷新并且元素不会附加到 DOM,您可能会遇到陈旧的引用异常。

    最好的方法是再次分配回元素。

    试试这个科。

    tr_elements=driver.find_elements(By.XPATH,"//tr[contains(@onclick, 'OpenSession ')]")
    
    for tr in range(len(tr_elements)):
       tr_elements=driver.find_elements(By.XPATH,"//tr[contains(@onclick, 'OpenSession ')]")
       tr_elements[tr].location_once_scrolled_into_view
       tr_elements[tr].click()
       time.sleep(3) # slow down the for loop
    

    将识别所有具有onclcick属性的tr元素,然后是iterate,然后再次搜索element。它将使用索引来使用each element,然后是scroll first,然后是click,一旦点击任何元素页面将是refreshed,然后它将在循环中再次捕获该元素,它是assined

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-07
      • 1970-01-01
      • 1970-01-01
      • 2022-07-07
      • 1970-01-01
      • 2011-07-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多