简体   繁体   English

使用 Python 在 Selenium 中单击按钮(元素不可交互)时出现问题

[英]Issues clicking a button (element not interactable) in Selenium using Python

I have a problem clicking the second button because i get this error message:我在单击第二个按钮时遇到问题,因为我收到以下错误消息:

selenium.common.exceptions.ElementNotInteractableException: Message: element not interactable

htlm button: html按钮:

<button class="btn btn-primary btn-fab" type="button" 
    <span class="mdi mdi-plus" aria-hidden="true"></span>
    <span class="sr-only">+</span>

<button class="btn btn-primary btn-fab" type="button" 
    <span class="mdi mdi-minus" aria-hidden="true"></span>
    <span class="sr-only">-</span>
        

my code:我的代码:

button = driver.find_element_by_css_selector('div.amount-control > button.btn.btn-primary.btn-fab > span.mdi.mdi-plus')
button.click()

what my code does is locating the second button, the problem is I have to locate <span class="mdi mdi-plus" aria-hidden="true"></span> to diferenciate both buttons but i think i have to click <button class="btn btn-primary btn-fab" type="button" not the span because it's not interactable.我的代码所做的是找到第二个按钮,问题是我必须找到<span class="mdi mdi-plus" aria-hidden="true"></span>来区分两个按钮,但我想我必须点击<button class="btn btn-primary btn-fab" type="button"不是跨度,因为它不可交互。

How can i click the <button> and not the span after locating the span.找到跨度后如何单击<button>而不是跨度。

You can receive the parent node of an element by the following.您可以通过以下方式接收元素的父节点。

button = driver.find_element_by_css_selector('div.amount-control > button.btn.btn-primary.btn-fab > span.mdi.mdi-plus')
actual_button = button.find_element_by_xpath('./..')

Furthermore, I would recommend you to use the following script to click an element in selenium, since selenium often has problems with clicking on elements.此外,我建议您使用以下脚本单击 selenium 中的元素,因为 selenium 在单击元素时经常出现问题。

try:
    element = driver.find_element(By.XPATH, path)
    driver.execute_script("arguments[0].click();", element)
except Exception as e:
    print(e)

Note that you just have to replace the path variable with your xpath.请注意,您只需将path变量替换为 xpath。

Your elements are not closed correctly.您的元素未正确关闭。 The </button> closing tag is missing in both cases.在这两种情况下都缺少</button>结束标记。 Please change your code to this:请将您的代码更改为:

<button class="btn btn-primary btn-fab" type="button" 
    <span class="mdi mdi-plus" aria-hidden="true"></span>
    <span class="sr-only">+</span>
</button>

<button class="btn btn-primary btn-fab" type="button" 
    <span class="mdi mdi-minus" aria-hidden="true"></span>
</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM