Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XPath to find elements that does not have an id or class

Tags:

xpath

How can I get all tr elements without id attribute?

<tr id="name">...</tr> <tr>...</tr> <tr>...</tr> 

Thanks

like image 271
priyank Avatar asked Mar 08 '10 19:03

priyank


People also ask

Is XPath faster than ID?

Technically speaking, By.ID() is the faster technique because at its root, the call goes down to document. getElementById(), which is optimized by most browsers. But, finding elements using XPath is better for locating elements having complex selectors, and is no doubt the most flexible selection strategy.

How do you find the XPath of an element in code?

Go to the First name tab and right click >> Inspect. On inspecting the web element, it will show an input tag and attributes like class and id. Use the id and these attributes to construct XPath which, in turn, will locate the first name field.

What is XPath ID?

XPath in Selenium is an XML path used for navigation through the HTML structure of the page. It is a syntax or language for finding any element on a web page using XML path expression. XPath can be used for both HTML and XML documents to find the location of any element on a webpage using HTML DOM structure.

How do I find the XPath of a list?

The simplest case would be to find the list first Webelemebt list = driver. findElement(By.name("optionsTab")); and then find the elements within that list List<Webelement> elements = list. findElements(By. xpath("//li"));


2 Answers

Pretty straightforward:

//tr[not(@id) and not(@class)] 

That will give you all tr elements lacking both id and class attributes. If you want all tr elements lacking one of the two, use or instead of and:

//tr[not(@id) or not(@class)] 

When attributes and elements are used in this way, if the attribute or element has a value it is treated as if it's true. If it is missing it is treated as if it's false.

like image 111
Welbog Avatar answered Oct 22 '22 02:10

Welbog


If you're looking for an element that has class a but doesn't have class b, you can do the following.

//*[contains(@class, 'a') and not(contains(@class, 'b'))] 

Or if you want to be sure not to match partial.

//*[contains(concat(' ', normalize-space(@class), ' '), ' some-class ') and  not(contains(concat(' ', normalize-space(@class), ' '), ' another-class '))] 
like image 44
miphe Avatar answered Oct 22 '22 01:10

miphe