Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XPath: Find element that contains text X and not Y

I'm attempting to find a web element using XPath in Selenium for Python. The web element should contain the text "Chocolate" but not include "Dark".

I've tried this syntax but not gotten it to work (be mindful of parantheses):

choco = driver.find_element_by_xpath("//*[text()[contains(., 'Chocolate')] and not[[contains(., 'Dark')]]]")

Here is the same code using line breaks and concatenation for readability:

choco = driver.find_element_by_xpath((
                                    "//*[text()[contains(., 'Chocolate')]" + 
                                    "and not[[contains(., 'Dark')]]]"
                                    ))
like image 894
P A N Avatar asked Jun 26 '16 14:06

P A N


People also ask

How do I search for text in XPath?

So, inorder to find the Text all you need to do is: driver. findElement(By. xpath("//*[contains(text(),'the text you are searching for')]"));

How will you write XPath if the tag has only text?

We will start to write XPath with //, followed by input tag, then we will use the select attribute, followed by its attribute name like name, id, etc, and then we will choose a value of attribute in single quotes. Here, (1 of 1) means exact match. It indicates that there is only one element available for this XPath.

What is text () in XPath?

XPath text() function is a built-in function of the Selenium web driver that locates items based on their text. It aids in the identification of certain text elements as well as the location of those components within a set of text nodes. The elements that need to be found should be in string format.

How do you write the XPath using contains?

The syntax for locating elements through XPath- Using contains() method can be written as: //<HTML tag>[contains(@attribute_name,'attribute_value')]


2 Answers

Please try following XPath and let me know if any errors occurs:

//*[contains(text(), "Chocolate")][not(contains(text(), "Dark"))]
like image 102
Andersson Avatar answered Oct 31 '22 17:10

Andersson


Here is the syntax with using just one set of square brackets.

For elements containing the word 'Chocolate' but not 'Dark', use:

//*[contains(text(), 'Chocolate') and not(contains(text(), 'Dark'))]

For just the text of the elements, use:

//text()[contains(., 'Chocolate') and not(contains(., 'Dark'))]

Given the following XML:

<doc>
  <e>Dark Chocolate</e>
  <e>Chocolate</e>
</doc>

The first expression results in:

> xpath -e "//*[contains(text(), 'Chocolate') and not(contains(text(), 'Dark'))]" test.xml 
<e>Chocolate</e>

The second expression results in:

> xpath -e "//text()[contains(., 'Chocolate') and not(contains(., 'Dark'))]" test.xml 
Chocolate
like image 20
Markus Avatar answered Oct 31 '22 18:10

Markus