1

Have the HTML code as below.and i want to locate the element using the text SOFTWATE.

<label _ngcontent-c5="" class="form-check-label" style="" xpath="1">
  <input _ngcontent-c5="" class="form-check-input ng-untouched ng-pristine ng-valid" type="checkbox">
  <!----> 
  <!---->
  <span _ngcontent-c5="" class="checkmark">
  </span>
  SOFTWARE 
</label>

Tried with the xpath //div[@class='filter-item-wrapper activate']//label[contains(text(),'SOFTWARE')], but no luck.

Anyone could please help to find the locate the element using the text 'SOFTWARE'

SirFartALot
  • 1,215
  • 5
  • 25
MVLS
  • 37
  • 3

4 Answers4

1

try with the following it may work.

//div[@class='filter-item-wrapper activate']//label[contains(.,'SOFTWARE')]
Murthi
  • 5,299
  • 1
  • 10
  • 15
  • Thanks, it worked. Could you please explain what is the use of '.' in [contains(.,'SOFTWARE')] and also the meaning of normalize-space(.) in xpath – MVLS Jun 28 '19 at 05:46
1

This is precisely why we always advise people to avoid using text() to access text nodes directly. It's nearly always better to use string() to access the string value of the containing element, and one of the big differences is that the result of string() is unaffected by adding or removing comments.

So use contains(string(), 'SOFTWARE') -- which can then be abbreviated to contains(., 'SOFTWARE'), because a call on string() is implicit when a string is required and you supply a node.

Michael Kay
  • 156,231
  • 11
  • 92
  • 164
0

Presumably you simply don't want to locate the element but you want to click() on the checkbox as well and to achieve that you have to induce WebDriverWait for the element to be clickable and you can use the following Locator Strategy:

  • Using CSS_SELECTOR:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "label.form-check-label>input.form-check-input.ng-untouched.ng-pristine.ng-valid[type='checkbox']"))).click()
    
  • Using XPATH:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//label[@class='form-check-label' and normalize-space()='SOFTWARE']/input[@class='form-check-input ng-untouched ng-pristine ng-valid']"))).click()
    
  • Note : You have to add the following imports :

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
0

You can try:

//div/descendant-or-self::label[normalize-space(.)='SOFTWARE']

This should strip out any additional leading or trailing whitespace before trying to match the text.

Ardesco
  • 7,281
  • 26
  • 49