Home > database >  Confirm if link is disabled selenium/Python
Confirm if link is disabled selenium/Python

Time:09-23

The below code finds the correct link from an unordered list in a browser, however the EC.element_to_be_clickable function doesn't work because if the link wasn't clickable, it will require the browser to be refreshed (to check again).

Instead, is there any way for the link to be checked if it is disabled (and click() if it isn't? The link will come in one of the below formats

<a class="Button disabled">Purchase</a>
<a class="Button">Purchase</a>

Code below

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

try:
    if len(driver.find_elements(By.XPATH, "//span[text()='$30.00']/../following-sibling::div/a[text()='Purchase']")) > 0:
        print("Found, now attempting to click link")
        WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//span[text()='$30.00']/../following-sibling::div/a[text()='Purchase']"))).click()

CodePudding user response:

To check if a link is disabled, ie. if its class contains 'disabled', just look for it in its class:

try:
    if len(driver.find_elements(By.XPATH, "//span[text()='$30.00']/../following-sibling::div/a[text()='Purchase']")) > 0:
    elem = driver.find_element(By.XPATH, "//span[text()='$30.00']/../following-sibling::div/a[text()='Purchase']")
        print("Found, now attempting to click link")
        if "disabled" in elem.get_attribute("class"):
            print("Link disabled! Refreshing page.")
            driver.refresh()
        else:
            elem.click()
  • Related