Selecting a link with Selenium Webdriver?

55,842

Solution 1

XPath is one of the most exact ways to point the element.

Try this:

driver.findElement(By.XPath("//li[@class='li_class']/a")).Click();

Solution 2

This should work:

driver.findElement(By.LinkText("Users")).click();

By LinkText is possible

Solution 3

Using a CSS selector:

a[href*=user.xhtml]

Here are some tips for writing cssSelector

 = --> Equals string
^= --> Starts with string
$= --> Ends with string
*= --> Contains 
~= --> Contains in a list

Solution 4

I agree with Christoph - Link text should work. But I follow a different approach which works for me all the time.

All the element that I need to locate or select I give them an id (without CSS there won't be any difference in view). This helps in readability of my test cases, writing functions for general stuff and improves maintainability of the code. Only for the dynamic generated code or places where I can't use id I go for different approach.

Share:
55,842
membersound
Author by

membersound

JEE + Frameworks like Spring, Hibernate, JSF, GWT, Vaadin, SOAP, REST.

Updated on July 09, 2022

Comments

  • membersound
    membersound almost 2 years

    How can I select a link with selenium webdriver?

    Selenium before would be done by:

        selenium.click("link=Users");
    

    But how can I do the same with webdriver?

    I thought about

        driver.findElement(By.partialLinkText("Users")).click();
    

    but this does not work. No link is clicked!

    <html>
    <body>
    <div id="mainpage" class="mainpage">
    <div id="pageid" class="pageid">
    <div id="body">
    
    <table>
    <tbody>
    <tr>
    <td>
    <table>
    <tbody>
    <tr>
    <td>
    <div id="id_menu" class="mymenu">
    <ul>
    <li class="li_class ">
    <a href="/user.xhtml">Users</a>
    

    stacktrace:

        org.openqa.selenium.NoSuchElementException: Unable to locate element: 
    {"method":"partial link text","selector":"Users"} Command duration or timeout: 11.36 
    seconds For documentation on this error, please visit: http://seleniumhq.org/exceptions
    /no_such_element.html Build info: version: '2.24.1', revision: '17205', time: '2012-06-19 
    17:28:14' System info: os.name: 'Windows XP', os.arch: 'x86', os.version: '5.1', 
    java.version: '1.7.0_02' Driver info: driver.version: RemoteWebDriver Session ID: 
    178449d1-4ff3-44f3-b35c-6a158db7c430 error at line: 34