【问题标题】:I need to click on a td, but selenium reports an error "selenium.common.exceptions.NoSuchElementException: Message: no such element"我需要点击一个td,但是selenium报错“selenium.common.exceptions.NoSuchElementException: Message: no such element”
【发布时间】:2021-11-17 20:19:39
【问题描述】:

这是页面的 HTML:

<td class="titulo_lateral" onclick="javascript: abreMenu(&quot;layer8&quot;);" style="cursor:pointer;">RELATÓRIOS</td>

我正在尝试这个:

driver.find_element_by_xpath("//*[@id='f']/table/tbody/tr/td/table[2]/tbody/tr/td")

【问题讨论】:

    标签: python html selenium html-table


    【解决方案1】:

    你确定td 以及相应的 XPath 已经在 Selenium 行执行时呈现在页面上吗?

    如果是这样,您可以尝试使用完整的 XPath 而不是相对的 XPath Copy Full XPath button pictured here

    【讨论】:

    • 我尝试使用完整的 xpath,但也没有用。
    【解决方案2】:

    你可以试试下面的xpath。

    //td[@class='titulo_lateral']
    

    //td[text()='RELATÓRIOS' and contains(@onclick,'abreMenu')]
    

    但首先你必须确定它在 HTMLDOM 中是否是唯一的。

    PS:如果我们在HTML DOM 中有唯一条目,请检查dev tools(谷歌浏览器)。

    检查步骤:

    Press F12 in Chrome -> 转到element 部分 -> 做一个CTRL + F -> 然后粘贴xpath 看看,如果你想要的element 用@ 得到高亮 987654330@匹配节点。

    一旦我们有了唯一匹配的 xpath。您可以尝试通过以下方法点击它。

    代码试用 1:

    time.sleep(5)
    driver.find_element_by_xpath("//td[text()='RELATÓRIOS' and contains(@onclick,'abreMenu')]").click()
    

    代码试用 2:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//td[text()='RELATÓRIOS' and contains(@onclick,'abreMenu')]"))).click()
    

    代码试用 3:

    time.sleep(5)
    button = driver.find_element_by_xpath("//td[text()='RELATÓRIOS' and contains(@onclick,'abreMenu')]")
    driver.execute_script("arguments[0].click();", button)
    

    代码试用 4:

    time.sleep(5)
    button = driver.find_element_by_xpath("//td[text()='RELATÓRIOS' and contains(@onclick,'abreMenu')]")
    ActionChains(driver).move_to_element(button).click().perform()
    

    进口:

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

    【讨论】:

    • 嗨@Cruisepandey!你发给我的代码都不起作用。我在 HTMLDOM 中进行了 xpath 查找,它是独一无二的。硒报告的错误是这样的:selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//td[text() ='REPORTS' and contains(@onclick,'abreMenu')]"}
    • 文本是RELATÓRIOS 不是REPORTS,请使用这个xpath //td[text()='RELATÓRIOS' and contains(@onclick,'abreMenu')]
    • 报错如下:selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//td[text()='RELATÓRIOS' and contains(@onclick,'abreMenu')]"}
    • 您需要先切换到框架,获取框架 xpath,然后将其放入driver.switch_to.frame(driver.find_element_by_xpath("frame xpath")),然后使用我上面的任何解决方案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-04
    • 2017-07-15
    • 1970-01-01
    • 2018-11-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多