roger_that
roger_that

Reputation: 9791

Firefox driver unable to detect webelement

I have been trying to get the anchor link via WebDriver but somehow, things aren't working as desired and I am not getting the element.

Below is the HTML Structure:

<div id="1">
   <table width="100%">
      <tr>
         <td>.....</td>
         <td>
           <ul class="bullet">
              <li>....</li>
              <li>....</li>
              <li>
                 <a href="/abc/myText.html?asq=ahsdyrg347rfbwljidwbkjab">myText</a>
              </li> // myText is the text I am searching for
           </ul>
         </td>
      </tr>
    </table>
    <div>....</div>
</div>

The <li> elements contains anchor tags with links only. No id or any other attribute they contain. The only difference is the text displayed by them and hence, I am passing myText to detect exactly what I need.

And for this, the java code I have been trying is:

   driver.get("url");

   Thread.sleep()    //waiting for elements to get loaded. Exceptional Handling not done.
   WebElement divOne = driver.findElement(By.id("1"));

   WebElement ul = divOne.findElement(By.className("bullet"));

  WebElement anchor = null;
    try{ 
        anchor = ul.findElement(By.partialLinkText("myText"));
    }catch(NoSuchElementException ex){
        LOGGER.warn("Not able to locate tag:" + linkText + "\n");
    }
   String myLink = anchor.getAttribute("href");   // null pointer exception

I don't understand why is this happening. What is the correct way to do this? Should I use some other method?

Upvotes: 0

Views: 177

Answers (4)

Amith
Amith

Reputation: 7008

Try using a WebDriver instance directly instead of WebElement instance...i.e., use driver instead of ul..

you can try with wait,

element = new WebDriverWait(driver,10).until(ExpectedConditions.visibilityOfElementLocated(By.linkText("myText")));

Upvotes: 0

MA1
MA1

Reputation: 2847

String myLink = anchor.getAttribute("href");   // null pointer exception

You are getting exception because you didn't set the anchor value, anchor variable is created and intialized to null and after that it is never updated.

I think the correct code should be below

String myLink = element.getAttribute("href");

Upvotes: 0

diazazar
diazazar

Reputation: 542

driver.findElement(By.xpath("//a[contains(text(),'myTest')]")); 

that searches for myTest text. I haven't tried the code, I hope it helps you

Upvotes: 1

A Paul
A Paul

Reputation: 8251

you can use any of the below. Should work for you

List<WebElement> anchor = driver.findElements(By.partialLinkText("myText"));

or

driver.findElements(By.linkText("myText"))

or

driver.findElements(By.Xpath("//a[contains(text(),'myText')]"));

Upvotes: 0

Related Questions