【问题标题】:How to get Selenium to recognise a button and click it?如何让 Selenium 识别按钮并单击它?
【发布时间】:2021-06-25 14:00:15
【问题描述】:

如何让 selenium python 识别 HTML 中的这个按钮?

我已经尝试过这个和其他标签来获得它

 driver.find_element_by_class_name('cookie-monster').clickbutton
        print('button was clicked')

这是按钮sn-p代码

<button class="cookie-monster__cta cookie-monster__cta--primary js-cookie-monster-accept">
<span class="glyphicon glyphicon-ok"></span>
Accept All Cookies
</button>

【问题讨论】:

    标签: python css selenium selenium-webdriver


    【解决方案1】:

    您的定位器错误。该类名为cookie-monster__cta,而不是.cookie-monsterjs-cookie-monster-accept 似乎是唯一的类名。用它来寻找你的元素。 此外,您应该在点击元素之前等待它们。

    from selenium.webdriver.support.wait import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.webdriver.common.by import By
    
    wait = WebDriverWait(driver, 20)
    wait.until(EC.element_to_be_clickable(
                    (By.CSS_SELECTOR, "js-cookie-monster-accept")))
    button = driver.find_element_by_css_selector("js-cookie-monster-accept")
    button.click()
    

    如果此定位器不是唯一的,则将类一个一个地添加到waitfind_element_by_css_selector,如下所示:

    .js-cookie-monster-accept.cookie-monster__cta
    

    【讨论】:

    • 如果可行,请接受答案或告知是否会出现其他问题。
    • 嗨,它现在出现一个错误,说没有定义等待。所以我放了Webdriverwait(driver,10).until(EC.element_to_be_clickable( 但是它说selectby 没有定义。
    • 将 selectby 更改为 By 并添加 import from selenium.webdriver.common.by import By
    • 现在抛出这条消息,也不点击按钮。 File "C:\Users\danin\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\support\wait.py", line 80, in until raise TimeoutException(message, screen, stacktrace) selenium.common.exceptions.TimeoutException: Message:
    • 嗨,我无法让它工作,所以我最终使用 xpath 来查找元素,它工作得更好,不过还是谢谢。
    猜你喜欢
    • 2023-04-06
    • 2020-02-24
    • 2022-08-18
    • 1970-01-01
    • 1970-01-01
    • 2022-01-28
    • 2020-10-22
    • 2021-09-25
    • 2011-11-12
    相关资源
    最近更新 更多