简体   繁体   English

使用Selenium和Python,如何检查按钮是否仍然可点击?

[英]Using Selenium and Python, how to check whether the button is still clickable?

so I am doing some web scraping using Selenium with Python and I am having a problem. 所以我正在使用Selenium和Python进行一些网络抓取,我遇到了问题。 I am clicking a Next button to move to the next page on a certain website, but I need to stop clicking it when I reach the last page. 我点击“下一步”按钮移动到某个网站的下一页,但是当我到达最后一页时,我需要停止点击它。 Now, my idea of doing it would be just to use some_element.click() in a try/except statement and wait until it gives me an error while the button is not clickable anymore. 现在,我这样做的想法只是在try / except语句中使用some_element.click()并等到它给我一个错误,而按钮不再可点击。 It seems though, .click() doesn't emit any signal of any kind, it doesn't throw an error when the button can't be clicked and it doesn't emit any true or false signal. 看来,.click()不会发出任何类型的信号,当按钮无法点击并且不发出任何真或假信号时,它不会抛出错误。

a code snippet I tried using: 我尝试使用的代码段:

while True:
    try:
       button = driver.find_element_by_class_name('Next_button')
       button.click()
    except:
       break

Is there any other way? 还有其他方法吗? Thanks and cheers. 谢谢和欢呼。

Without knowing more about your example target, the minimal that can be said is that a clickable attribute would have an 'href' attribute. 在不了解您的示例目标的情况下,可以说的最小值是可点击属性具有'href'属性。
You can use the get_attribute property of an element: 您可以使用元素的get_attribute属性:

button = driver.find_element_by_class_name('Next_button')
href_data = button.get_attribute('href')
if href_data is None:
  is_clickable = False

Gets the given attribute or property of the element. 获取元素的给定属性或属性。

This method will first try to return the value of a property with the given name. 此方法将首先尝试返回具有给定名称的属性的值。 If a property with that name doesn't exist, it returns the value of the attribute with the same name. 如果不存在具有该名称的属性,则返回具有相同名称的属性的值。 If there's no attribute with that name, None is returned. 如果没有具有该名称的属性,则返回None。

Values which are considered truthy, that is equals “true” or “false”, are returned as booleans. 被视为真实的值,即等于“真”或“假”,将作为布尔值返回。 All other non-None values are returned as strings. 所有其他非None值都以字符串形式返回。 For attributes or properties which do not exist, None is returned. 对于不存在的属性或属性,返回None。

More on Using get_attribute 有关使用get_attribute更多信息

You could also try is_displayed or is_enabled 您也可以尝试is_displayedis_enabled

使用它来获取类element.get_attribute(“class”)并检查类列表是否包含来自html框架的特征类(例如“disable”),用于描述不可点击的按钮

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

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