warchest warchest - 4 months ago 8
Python Question

How to find element based on text and class with Selenium?

I have an html table, and I want to find the

td
element in
tbody
based on the text and if it doesn't contain a certain class. It should ignore anything in
thead
even if the text is present.

...

<div id="mytable">
<div>
<table>
<thead>
<tr>....</tr>
...
</thead>
<tbody>
<tr>
<td class="inactive">3</td>
<td>4</td>
</tr>
</tbody>
</table>
</div>
</div>

...


Here is the code:

def do_click(user_input):
browser = webdriver.Firefox()
browser.get(url)

mytable_div = browser.find_element_by_id("mytable")
element = mytable_div.find_element_by_xpath("//div/table/tbody/td[contains(text()='%s')]" % user_input)

if element:
element.click()


So if the
user_input = 3
, the table element should NOT be clicked because it has the class
inactive
even though the text is present.

If the
user_input = 4
, then the table element should be clicked since it does not have a inactive class and the text is present.

Currently the code doesn't work because my xpath expression is invalid, but I'm not sure what the correct way to check for both the class and the text would be.

Answer

You are on the right track. contains() is a function and expects 2 arguments to be passed in - a string where to look and a substring - what to look. Fix your expression:

"//div/table/tbody//td[contains(text(), '%s')]" % user_input

You can also use a dot instead of text() in this case.

And, to also check for the class being not inactive, add "not contains" check:

"//div/table/tbody//td[contains(., '%s')][not(contains(@class, 'inactive'))]" % user_input

As for the logic, handle the NoSuchElementException exception which, if raised, would mean the element was not found, click the element if no exception was raised:

from selenium.common.exceptions import NoSuchElementException

try:
    element = mytable_div.find_element_by_xpath("//div/table/tbody//td[contains(., '%s')][not(contains(@class, 'inactive'))]" % user_input)
    element.click()
except NoSuchElementException:
    print("Element not found")
Comments