简体   繁体   中英

How to search for the text within an “a href” tag and click?

I've got a table with a bunch of links. The IDs are all unique but do not correspond to the actual text that is displayed so I'm having some trouble.

Ex.

<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 within the ahref (ie. Project 1) and I want to search for it and click 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've been using

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

(projectname is a variable that changes every iteration) I think it works to find the element since the script runs but it doesn't click. I think it's because I'm not actually searching for the ahref and just for the text?

Here is the Answer to your Question:

If you want to click the 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 Project 1 part is dynamic so you can try to construct a separate function() for clicking these links. Call the function with all the projectnames one by one as follows (the function is in Java consider to convert as per your required language binding):

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

Now you can call from your main() class as: clickProject(Project1)

Let me know if this Answers your Question.

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

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

The .find_element_by_partialLinkText() locator strategy should account for any extra whitespace padding due to the extra span element.

Note : I write Java, so the above Python syntax may be off. But those methods must exist.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM