Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I select an empty element in XPath?

Tags:

selenium

xpath

We select elements with Django 1.4 tests and Selenium like this:

self.assertEqual(1, len(self.selenium.find_elements_by_xpath("//a[@href='#'][@class='button save-as'][@title='Save As...'][text()='Save As']")))

(The class inherits from LiveServerTestCase).

The problem is that sometimes there are elements without text, and if we select with [text()=''] it fails (the len is 0). How can I select elements without text?

Update: Because [text()=''] didn't work, I had to assert two lines to assert no text:

self.assertEqual(1, len(self.selenium.find_elements_by_xpath("//a[@href='#'][@class='button properties'][@title='Properties']")))
self.assertEqual("", self.selenium.find_element_by_xpath("//a[@href='#'][@class='button properties'][@title='Properties']").text)

Now I can assert the same with one line:

self.assertEqual(1, len(self.selenium.find_elements_by_xpath("//a[@href='#'][@class='button properties'][@title='Properties'][not(text())]")))
like image 599
Uri Avatar asked May 21 '14 09:05

Uri


People also ask

What is text () function in XPath?

The XPath text() function is a built-in function of selenium webdriver which is used to locate elements based on text of a web element. It helps to find the exact text elements and it locates the elements within the set of text nodes. The elements to be located should be in string form.

What is TD and TR in XPath?

The < tr > tag in the table indicates the rows in the table and that tag is used to get information about the number of rows in it. Number of columns of the web table in Selenium are calculated using XPath (//*[@id='customers']/tbody/tr[2]/td).

How do you find the XPath of an nth element?

By adding square brackets with index. By using position () method in xpath.


1 Answers

You could use XPath's not() function.

//a[@href='#'][@class='button save-as'][@title='Save As...'][not(text())]
like image 126
Matt Deacalion Avatar answered Oct 08 '22 07:10

Matt Deacalion