selenium.common.exceptions.NoSuchElementException在使用Selenium和Python识别要点击的元素时出错。

问题描述 投票:0回答:1

尽管我尝试了很多次,但还是无法执行以下操作。

我需要降落在一个包含一个或多个表格rowscolumns的页面上。对于每一个(按顺序),我需要点击一个箭头,打开一个弹出窗口,关闭窗口,然后冲洗和重复。

遇到的问题: 我无法点击该项目

错误。

类'selenium.common.exceptions.NoSuchElementException'。

提示错误的代码片段。

[...]
    driver = webdriver.Chrome('chromedriver.exe')
    chrome_options = webdriver.ChromeOptions()
    chrome_options.add_argument("--incognito")


    # MODIFY URL HERE
    driver.get(url)
[..]
try:
        # arf = driver.find_element_by_name("ctl00_ContentPlaceHolder1_d_dettaglio_ctl02_button1").click()
        arf = driver.find_element_by_xpath('//input[@id="ctl00_ContentPlaceHolder1_d_dettaglio_ctl02_button1"]').click()
        pprint.pprint(arf)
    except NoSuchElementException:
        print ("error!", NoSuchElementException)
        driver.close()
        exit()

我需要与之交互的HTML元素

                        <td align="center">
                            <input type="image" name="ctl00$ContentPlaceHolder1$d_dettaglio$ctl02$button1" id="ctl00_ContentPlaceHolder1_d_dettaglio_ctl02_button1" src="../images/spunta_maggiore.gif" style="height:22px;width:22px;border-width:0px;">
                        </td>

我已经尝试过的事情。

  • driver.find_element_by_xpath (//input[@id etc...])或 driver.find_element_by_xpath('//input[@name])
  • driver.find_element_by_name("ctl00_ContentPlaceHolder1_d_dettaglio_ctl02_button1").click()
  • driver.find_element_by_id("ctl00_ContentPlaceHolder1_d_dettaglio_ctl02_button1").click()

在这两种情况下,都会引发一个no element found异常。

我到底做错了什么?

python-3.x selenium xpath css-selectors nosuchelementexception
1个回答
0
投票

所需的元素是一个动态元素,所以要点击该元素,你必须诱导 WebDriverWait 对于 element_to_be_clickable() 您可以使用以下任何一种方式 定位策略:

  • 使用 CSS_SELECTOR:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input[type='image'][name*='ContentPlaceHolder'][id*='d_dettaglio'][src*='images/spunta_maggiore']"))).click()
    
  • 使用 XPATH:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[contains(@name, 'ContentPlaceHolder') and contains(@id, 'd_dettaglio')][@type='image' and contains(@src, 'images/spunta_maggiore.gif')]"))).click()
    
  • 说明: : 你必须添加以下导入。

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    

引用

你可以在以下网站找到一些相关的讨论 NoSuchElementException 中。

© www.soinside.com 2019 - 2024. All rights reserved.