Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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. 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.

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.

like image 407
Ivan Bilan Avatar asked Dec 25 '22 18:12

Ivan Bilan


2 Answers

Without knowing more about your example target, the minimal that can be said is that a clickable attribute would have an 'href' attribute.
You can use the get_attribute property of an element:

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.

Values which are considered truthy, that is equals “true” or “false”, are returned as booleans. All other non-None values are returned as strings. For attributes or properties which do not exist, None is returned.

More on Using get_attribute

You could also try is_displayed or is_enabled

like image 138
Dan O'Boyle Avatar answered Jan 14 '23 13:01

Dan O'Boyle


Use this to get classes element.get_attribute("class") and check if list of classes contains characteristic class (for example "disable") from your html framework which is used to describe unclickable buttons

like image 34
Bartłomiej Bartnicki Avatar answered Jan 14 '23 14:01

Bartłomiej Bartnicki