How do I select an empty element in XPath?

13,865

You could use XPath's not() function.

//a[@href='#'][@class='button save-as'][@title='Save As...'][not(text())]
Share:
13,865
Uri
Author by

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, 2022

Comments

  • Uri
    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
    Uri about 10 years
    It 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
    Matt Deacalion about 10 years
    Ah, 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
    Uri about 10 years
    Yes, some elements contain text and some are empty. They are different elements.
  • Uri
    Uri about 10 years
    By the way, do you know why [not(text())] works and [text()=''] doesn't?
  • Matt Deacalion
    Matt Deacalion about 10 years
    I'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.