2

I am driving myself bonkers with this.

I have three form fields in a form:

  1. Customer: required dropdown field
  2. Weight: required text field
  3. Status: optional text field

Each element has that label. The required fields' labels contain a span with an asterisk.

I'm using Xpather in Chrome. When I search for this, I receive 2 results, when I should get 3:

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

This makes no sense to me At All.

Customer, which is working:

<label for='customer-field'>
  <span class='required-marker'>*</span>
  Customer
  <input id='customer-field' type='text' />
</label>

Weight, which is not working:

<label class='control-label'>
  <span id='ctl01_requiredMarker' class='required-marker'>*</span>
  Weight
</label>

Status, which is working:

<label class='control-label'>
  Status
</label>

The only workaround that works for me is removing the required marker from the Weight label container. However, that doesn't explain how "Customer" gets matched at all.

Noteworthy: I'm trying to automate testing this page, so I can't really remove that span tag.

What's going on? And/or what do I do?

XtinaS
  • 194
  • 3
  • 15

4 Answers4

8

Try changing your XPath to the following:

//*[text()[contains(.,'t')]]

The source of this fix breaks it down far better than I could've done, so refer to that for detailed explanation! I've tested it myself using the XPath Checker extension for Firefox, and it matches your three items.

Community
  • 1
  • 1
Tetrinity
  • 1,105
  • 8
  • 20
1

Try with the below method

driver.findElement(By.xpath("//span[@class='required-marker']/..")).getText().contains("Weight")

Please Let me know above method is working or not.

user3487861
  • 340
  • 2
  • 2
0

I think your html is where the issue lies.

This is probably what your html should look like:

<span class='required-marker'>*
    <label for='customer-field'>Customer</label>
    <input id='customer-field' type='text' />
</span>
<span id='ctl01_requiredMarker' class='required-marker'>*
    <label class='control-label'>Weight</label>
</span>
<label class='control-label'>Status</label>
Richard
  • 8,961
  • 3
  • 38
  • 47
0

Are you using Selenium or WebDriver? What does WebDriver return as a response? Also make sure you add a "." before the xpath like .//*[contains(text(),'t')]

What does this print?

List<WebElement> elements = driver.findElement(By.xpath(".//*[contains(text(),'t')]"));
s.o.p(elements.size());
nilesh
  • 14,131
  • 7
  • 65
  • 79