【问题标题】:Selenium WebDriver - Click a Javascript ButtonSelenium WebDriver - 单击 Javascript 按钮
【发布时间】:2021-09-03 13:43:08
【问题描述】:

这是我想点击的按钮:

<a id="BUTTON_GROUP_ITEM_A5_btn4_acButton" ct="B" st="" href="javascript:void(0);" ti="0" tabindex="0" class="urBtnStd" ocl="sapbi_buttonGroup_callCustomScript([['CUSTOMFUNCTION','ExportXLSCM',0]],event);" onkeydown="ur_Button_keypress(event);" onclick="ur_Button_click(event);" style="min-width: !important;text-align:center;overflow:visible;">Export to Excel</a>

我使用了以下方法:

button = driver.find_element_by_link_text('Export to Excel')
button.click()

button = driver.find_element_by_xpath("//a[contains(@id, 'BUTTON_GROUP_ITEM_A5_btn4_acButton')]")  
button.click()

#Using full xPath
button = driver.find_element_by_xpath("/html/body/table[2]/tbody/tr/td/div[2]/div[1]/div/table[1]/tbody/tr/td[3]/div/span[5]/a")
button.click()

但他们都给selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element错误

知道如何解决这个问题,甚至打印页面上的所有元素,以便我可以找出要“点击”的内容吗?我尝试了很多方法,但都给出了同样的错误。谢谢!

【问题讨论】:

    标签: javascript selenium selenium-webdriver selenium-chromedriver


    【解决方案1】:
    button = driver.find_element_by_link_text('Export to Excel')
    button.click()
    

    说明:

    如果上面给出了NoSuchElementException,我可能会怀疑它在 iframe 中,如果碰巧在这种情况下,你需要先切换到 iframe 并继续使用这个 web 元素。

    代码:

    wait = WebDriverWait(driver, 10)
    wait.until(EC.frame_to_be_available_and_switch_to_it((By.XPATH, "iframe xpath here")))
    wait.until(EC.element_to_be_clickable((By.PARTIAL_LINK_TEXT, "Export to Excel"))).click()
    

    进口:

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

    如果这不起作用,我可能会询问您的驱动程序配置。是全屏打开浏览器吗?

    【讨论】:

    • 完美!!这就像一个魅力..你救了我无数小时的痛苦:-) 但我没有得到的是为什么我需要切换到 iframe?例如,为什么完整的 XPath 不起作用?有没有办法在任何 XPath 上工作而无需切换或任何额外工作?
    【解决方案2】:

    我找到了一个使用 Helium 库更简单的解决方案:

    pip install helium
    

    更多信息:https://selenium-python-helium.readthedocs.io/en/latest/api.html

    from helium import *
    start_chrome(url)
    click('Export to Excel')
    

    就这么简单! Helim 非常简单且用户友好。强烈推荐。

    【讨论】:

    • 这是不道德的。氦气没有被标记。永远不要这样做!
    • 我不知道这有什么不道德的?!!关键是为开发人员社区提供最佳解决方案,显然这是一个更简单的解决方案,考虑到总体目标。我不知道氦气,如果我知道它很容易,那会节省我几个小时。话虽如此,我很感谢您的帮助,因此我已将您的答案作为已接受的答案返回。我希望这能让你开心。谢谢。
    • 不,在初始阶段从未提及您正在寻找不同的库,最初的问题是单击 JS 按钮,加上您已标记 Selenium 。你可以用 Selenium 做很多事情。而 Helium 的 API 仅适用于 Python,主要适用于 FF 和 Chrome。因此,如果有人遇到同样的问题,但如果它是 safari 浏览器,那么 Helium 将无法工作。是的,您不需要在 Helium 中切换到 iframe。但它有它自己的缺点。但是,如果您真的认为您的解决方案应该是可接受的答案,请继续……将其标记为已接受的答案。
    • 感谢您的反馈。两个答案都在那里,因此由其他人选择最适合他们的答案。我想给你应得的荣誉,所以我很乐意将你的答案保留为已接受的答案。谢谢☺️
    猜你喜欢
    • 1970-01-01
    • 2020-09-04
    • 1970-01-01
    • 1970-01-01
    • 2019-05-16
    • 1970-01-01
    • 1970-01-01
    • 2016-05-31
    • 2016-01-30
    相关资源
    最近更新 更多