Home > Back-end >  Selenium XPath Selector for link with no text
Selenium XPath Selector for link with no text

Time:05-04

Base on this anchor link with no text inside but different children div's what I am trying to do is click on the element that takes me to another page. Sadly I have not be able to get it. Any advice? my selectors options that I have tried are below

<div id="divProducts" style="display: inline-block; text-align: center; width:100%;">
 <a  tabindex="0" href="#" onclick="ProdOnClick(); $('#divNewApp').load('NewApplication'); return false;">
   <div style="width: 15%; display: inline-block;" aria-label="Life,">
      Life
   </div>
   <div style="width: 30%; display: inline-block;" aria-label="PA Wealth Transfer Trust,">
      PA Form
   </div>
   <div style="width: 35%; display: inline-block; font-size: large;" >
      MT Form
   </div>
 </a>
</div>

Selenium selectors options used but with no results;

By.xpath("//*[@id='divProducts']/a[1]");
By.xpath("//*a[contains(.,'Life')]");
By.xpath("//*[@id='divProducts']/a[contains(.,'MT Form')]");
By.partialLinkText("MT Form");
By.linkText("MT Form");
By.cssSelector("a:nth-child(1) div:nth-child(3)");
By.cssSelector("#divProducts > a:nth-child(1)");

PLEASE HELP!

CodePudding user response:

As per the HTML cliecking on either of the link texts should navigate to the same destination page.


Solution

To click on the element you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following locator strategies:

  • Using PARTIAL_LINK_TEXT:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.PARTIAL_LINK_TEXT, "Life"))).click()
    
  • Using CSS_SELECTOR:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a.listProd.grayButton.roundCorners.shadow[onclick^='ProdOnClick'] div[aria-label='Life,']"))).click()
    
  • Using XPATH:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[@class='listProd grayButton roundCorners shadow' and starts-with(@onclick, 'ProdOnClick')]/div[@aria-label='Life,']"))).click()
    
  • 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:

I dont have the required reputations to comment, so adding - try recording the scenario with Selenium IDE and see what locator gets generated. use that, it may help.

  • Related