YozSap YozSap - 1 year ago 58
Python Question

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.


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

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?

Answer Source

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()


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


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download