Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XPath partial of attribute known

Tags:

I know the partial value of an attribute in a document, but not the whole thing. Is there a character I can use to represent any value? For example, a value of a label for an input is "A. Choice 1". I know it says "Choice 1", but not whether it will say "A. " or "B. " before the "Choice 1". Below is the relevant HTML. There are other attributes for the input and the label, but they are not the same every time the page is rendered, so I can't use them as references:

<tr> <td><input type="checkbox" /><label>A. Choice 1</label></td> </tr><tr>     <td><input type="checkbox" /><label>B. Choice 2</label></td> </tr><tr> <td><input type="checkbox" /><label>C. Choice 3</label></td> </tr><tr>      <td><input type="checkbox" /><label>D. Choice 4</label></td> </tr> 

This is the XPath expression I'm using to select the input next to the label with the value of "Choice 1", except that the A is in front of it in the HTML:

//td[label="Choice 1"]/input 

I don't know if the A in the HTML will be an A, B, or C, etc. But I do know that the correct input will always have the Choice 1 text next to it. How do I say to select it if the label contains Choice 1, as opposed to being equal to choice 1?

like image 286
avaleske Avatar asked May 14 '09 00:05

avaleske


People also ask

How do you locate an element by partially comparing its attribute in XPath?

We can identify elements by partially comparing to its attributes in Selenium with the help of regular expression. In xpath, there is contains () method. It supports partial matching with the value of the attributes. This method comes as useful while dealing with elements having dynamic values in their attributes.

What is contain in XPath?

contains() in Selenium is a function within Xpath expression which is used to search for the web elements that contain a particular text. We can extract all the elements that match the given text value using the XPath contains() function throughout the webpage.

How do I start with XPath?

Using XPath- starts-with method, we can write the Java code along with the dynamic XPath location as: findElement(By. xpath("//*[starts-with(@id,'lst')]"));


1 Answers

Your XPath expression should look like this:

//td[contains(@label, 'Choice 1')]/input 

You select all td elements that have a label that contains Choice 1 and then you select the input elements inside these td elements.

EDIT: Tomalak's comment correctly suggests an improvement to prevent a match against 'Choice 11' (or 'Choice 12345', ...).

like image 64
Ronald Wildenberg Avatar answered Sep 27 '22 20:09

Ronald Wildenberg