How do I search for text in the "a href" tag and click?

I have a table with a bunch of links. The IDs are unique but do not match the actual text that is displayed, which is why I am having problems.

Ref.

<tr>
  <td><a id="011" href="/link">Project 1</a></td>
</tr>
<tr>
  <td><a id="235" href="/link">Project 2</a></td>
</tr>
<tr>
  <td><a id="033" href="/link">Project 3</a></td>
</tr>
<tr>
  <td><a id="805" href="/link">Project 4</a></td>
</tr>

      

I only know the text inside ahref (i.e. Project 1) and I want to search and click on it. I haven't been able to figure this out and I've been playing around with find_element_by_xpath for a while.

I used

selectproject = browser.find_element_by_xpath("//a[contains(.,projectname)]").click();

      

(the project name is a variable that changes every iteration) I think this works to find the element as the script is executing but it won't click. I guess it is because I am not actually looking for ahref and just for text?

+3


source to share


2 answers


Here is the answer to your question:

If you want to click a link with text Project 1

, you can use the following line of code:

browser.find_element_by_xpath("//a[contains(text(),'Project 1')]").click()

      

or

browser.find_element_by_xpath("//a[@id="011"][contains(text(),'Project 1')]").click()

      



Update:

As you mentioned, the part Project 1

is dynamic, so you can try to build a separate one function()

for these links to click. Call the function with all project names one by one like this (the function is in to convert according to your required language binding): Java

public void clickProject(String projectName)
{
    browser.findElement(By.xpath("//a[.='" + projectName + "']")).click();
}

      

Now you can call from your class main()

like this:clickProject(Project1)

Let me know if this answers your question.

+1


source


If your requirement is to "click on the Project 1 link", you must use that as a locator. No need to mess with XPath.

    browser.find_element_by_linkText("Project 1").click();
    // or the more flexible
    browser.find_element_by_partialLinkText("Project 1").click();

      



The locator strategy .find_element_by_partialLinkText()

should accommodate any additional padding due to the extra element span

.

Note . I am writing Java, so the above Python syntax can be turned off. But these methods must exist.

0


source







All Articles