【问题标题】:selenium.common.exceptions.NoSuchElementException error trying to identify element to click using Selenium and Pythonselenium.common.exceptions.NoSuchElementException 错误尝试使用 Selenium 和 Python 识别要单击的元素
【发布时间】:2020-10-02 02:37:32
【问题描述】:

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

我需要登陆包含一个或多个表格行/列的页面。对于每个(依次),我需要单击打开弹出窗口的箭头,关闭窗口,然后冲洗并重复。

问题:我无法点击该项目

错误:

类'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()

在这两种情况下,都会引发未找到元素异常。

我做错了什么?

【问题讨论】:

  • 您是否尝试过等待元素加载?例如WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.XPATH, 'xpath of your choice here'))).click()

标签: python-3.x selenium xpath css-selectors nosuchelementexception


【解决方案1】:

想要的元素是动态元素,所以点击元素你必须诱导WebDriverWaitelement_to_be_clickable(),你可以使用以下Locator Strategies之一:

  • 使用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 上找到一些相关讨论:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-23
    • 2021-08-28
    • 1970-01-01
    • 1970-01-01
    • 2016-01-19
    • 2021-10-14
    相关资源
    最近更新 更多