User11112312312
User11112312312

Reputation: 3

Cannot access the element using the "Contains" keyword (Selenium,Python)

I'm trying to access the following element using the contains keyword but I fail every time:

<div class="country_item " data-region="4">
<label class="chk-label-active" for="country_255">Bulgaria</label>
<div class="jcf-class-save-checkbox chk-area chk-checked">
<span/>
</div>
<input id="country_255" class="save-checkbox jcf-hidden" data-allowlist="378,438,183" name="jform[country][]" value="255" data-currency="2" data-bond_count="19" checked="checked" type="checkbox"/>
</div>

I tried:

1. //*[contains(text(), 'Bulgaria')])
2. //*[@id='country']/div[15][@label='Bulgaria']

(it's a list of countries and Bulgaria is under div[15]

Can anyone help me to find out what the problem is?

Upvotes: 0

Views: 862

Answers (2)

Monika
Monika

Reputation: 732

You can try following Xpath options:

//label[contains(.,'Bulgaria')]
//label[contains(text(),'Bulgaria')]
//div[contains(@class,'country_item')]/label[contains(.,'Bulgaria')]

Upvotes: 0

FrankTheTank_12345
FrankTheTank_12345

Reputation: 580

 //*[contains(text(), 'Bulgaria')])

To break this down,

  • * is a selector that matches any element (i.e. tag) -- it returns a node-set.
  • The [] are a conditional that operates on each individual node in that node set. It matches if any of the individual nodes it operates on match the conditions inside the brackets.
  • text() is a selector that matches all of the text nodes that are children of the context node -- it returns a node set.
  • contains is a function that operates on a string. If it is passed a node set, the node set is converted into a string by returning the string-value of the node in the node-set that is first in document order. Hence, it can match only the first text node in your element -- namely BLAH BLAH BLAH. Since that doesn't match, you don't get a in your results.

You need to change this to

 //*[text()[contains(.,'Bulgaria')]]
  • * is a selector that matches any element (i.e. tag) -- it returns a node-set.
  • The outer [] are a conditional that operates on each individual node in that node set -- here it operates on each element in the document.
  • text() is a selector that matches all of the text nodes that are children of the context node -- it returns a node set.
  • The inner [] are a conditional that operates on each node in that node set -- here each individual text node. Each individual text node is the starting point for any path in the brackets, and can also be referred to explicitly as . within the brackets. It matches if any of the individual nodes it operates on match the conditions inside the brackets.
  • contains is a function that operates on a string. Here it is passed an individual text node (.). Since it is passed the second text node in the <Comment> tag individually, it will see the 'Bulgaria' string and be able to match it.

Upvotes: 2

Related Questions