How do I select an empty element in XPath?

2020-03-03 06:38发布

问题:

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

回答1:

You could use XPath's not() function.

//a[@href='#'][@class='button save-as'][@title='Save As...'][not(text())]