Home > OS >  Python Selenium - find item in a list
Python Selenium - find item in a list

Time:11-12

I have the following:

<a href="/firewall_aliases.php" class="navlnk">Aliases</a>
<a href="/firewall_aliases.php" class="navlnk">NAT</a>
<a href="/firewall_aliases.php" class="navlnk">Rules</a>

I can't seem to be able to locate the element with text Aliases. Is it possible to do?

Can anyone help me out?

CodePudding user response:

You can use the following XPath locator:

//a[text()="Aliases"]

For more uniqueness you can use

//a[@href="/firewall_aliases.php" and (text()="Aliases")]

Or even

//a[@href="/firewall_aliases.php" and (@class="navlnk") and (text()="Aliases")]

CodePudding user response:

To locate the element with text as Aliases you can use either of the following Locator Strategies:

  • Using link_text:

    element = driver.find_element(By.LINK_TEXT, "Aliases")
    
  • Using css_selector:

    element = driver.find_element(By.CSS_SELECTOR, "a.navlnk[href*='firewall_aliases']")
    
  • Using xpath:

    element = driver.find_element(By.XPATH, "//a[text()='Aliases' and contains(@href, 'firewall_aliases')]")
    

Ideally, to locate the element you need to induce WebDriverWait for the visibility_of_element_located() and you can use either of the following Locator Strategies:

  • Using LINK_TEXT:

    element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.LINK_TEXT, "Aliases")))
    
  • Using CSS_SELECTOR:

    element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "a.navlnk[href*='firewall_aliases']")))
    
  • Using XPATH:

    element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//a[text()='Aliases' and contains(@href, 'firewall_aliases')]")))
    
  • Note : You have to add the following imports :

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

CodePudding user response:

You can use like:

//*[text()="Aliases"]

another way is

//a[@href="/firewall_aliases.php" and (text()="Aliases")]
  • Related