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.

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?

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

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.

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