warchest warchest - 1 year ago 104
Python Question

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

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

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


<div id="mytable">
<td class="inactive">3</td>


Here is the code:

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

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:

So if the
user_input = 3
, the table element should NOT be clicked because it has the class
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 Source

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

    element = mytable_div.find_element_by_xpath("//div/table/tbody//td[contains(., '%s')][not(contains(@class, 'inactive'))]" % user_input)
except NoSuchElementException:
    print("Element not found")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download