【问题标题】:How can i click an <a> button inside 2 divs in selenium python?如何在 selenium python 的 2 个 div 中单击 <a> 按钮?
【发布时间】:2021-04-13 06:50:06
【问题描述】:

我正在尝试让 selenium click Button1 但由于某些原因,我收到以下错误:

selenium.common.exceptions.NoSuchElementException: 消息:无法 定位元素:Button1

我相信错误正在发生,因为它位于 div/ul/li 标记内,但我也不知道该怎么做,我被卡住了。

HTML:

<div id="contentArea">
<div class="pageNavigation" id="pageNavigation">
    <ul>
        <li>

            <a href="#">Button1</a>

        </li>
        <li class="last">       

            <a href="#">Button2</a> 
                                            
        </li>
    </ul>
</div>
</div>

Python 代码:

from selenium import *

driver = webdriver.Firefox()
driver.set_window_size(1366, 768, driver.window_handles[0])
driver.get("https://localhost/mypage/index.php")
driver.find_element_by_link_text('Button1').click()

编辑:我发现html是通过javascript生成的。我的错。

【问题讨论】:

    标签: python html selenium button


    【解决方案1】:

    您可以尝试以下方法

    driver.find_element_by_xpath("//*[text()='Button1']").click()
    

    或者像你说的那样尝试定位div/ul/li中的元素

    driver.find_element_by_xpath("//div[@class='pageNavigation']/ul[1]/li[1]/a[1]").click()
    

    如果由于某种原因这不起作用,请尝试使用ActionChains

    为此,您需要导入模块

    from selenium.webdriver.common.action_chains import ActionChains
    

    然后用它来点击元素,
    在某些情况下,这对我来说是救命稻草

    action = ActionChains(driver)
    element = driver.find_element_by_xpath("//*[text()='Button1']")
    action.click(on_element=element).perform()
    

    【讨论】:

    • 您的回复很棒!但我想我发现了它为什么不起作用,因为 html 是通过 javascript 生成的。
    • 如果是这种情况你可以试试——driver.execute_script("document.getElementsByClassName('pageNavigation')[0].click()")
    • 我很遗憾地收到以下错误selenium.common.exceptions.JavascriptException: Message: TypeError: document.getElementsByClassName(...)[0] is undefined 无论如何感谢您的帮助,我会以某种方式解决它! :)
    猜你喜欢
    • 2017-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多