How do I select an empty element in XPath?
You could use XPath's not()
function.
//a[@href='#'][@class='button save-as'][@title='Save As...'][not(text())]
![Uri](https://i.stack.imgur.com/3upN5.jpg?s=256&g=1)
Uri
I'm a software programmer and sometimes an entrepreneur. I recently launched Speedy Match - a new matching/dating website for singles in Hebrew and English. Speedy Match is available for Speedy Net users. I also launched Speedy Net in Python and Django. I also created Speedy Composer, Speedypedia and Speedy Whois. All these projects are free software & open source. My personal homepage (with links to my profile on GitHub, LinkedIn and more).
Updated on June 28, 2022Comments
-
Uri about 2 years
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())]")))
-
Uri about 10 yearsIt works, just one fix - it's
[not(text())]
and not[text()='Save As' or not(text())]
- there is only one option of no text. -
Matt Deacalion about 10 yearsAh, so you know before hand that the elements should be empty? I read your question as you weren't sure what the element contained. Edited.
-
Uri about 10 yearsYes, some elements contain text and some are empty. They are different elements.
-
Uri about 10 yearsBy the way, do you know why
[not(text())]
works and[text()='']
doesn't? -
Matt Deacalion about 10 yearsI'm not sure, I pulled this out of some of my old code. I think it has something to do with an empty node (no children) and a text node containing an empty string (children) being treated differently in XPath.