0

How to locate the element using xpath through Selenium

Code trial:

By.xpath("//*[contains(@class,'a-size-mini a-spacing-none a-color-base s-line-clamp-2') and contains(text(), \"Men's Downshifter 9 Training Shoes\")]"));

HTML:

<h2 class="a-size-mini a-spacing-none a-color-base s-line-clamp-2">
    <a class="a-link-normal a-text-normal" href="/Nike-Downshifter-Running-Shoes-Anthracite/dp/B07H84PMGS/ref=sr_1_3?dchild=1&amp;keywords=NIKE+TRAINERS+FOR+MEN&amp;qid=1578766779&amp;sr=8-3">
    
<span class="a-size-base-plus a-color-base a-text-normal">Men's Downshifter 9 Training Shoes</span>
            
       </a>

    
</h2>
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
learner
  • 1
  • 1

2 Answers2

1

Closure ]

By.xpath("//*[contains(@class,'a-size-mini a-spacing-none a-color-base s-line-clamp-2') and contains(text(), \"Men's Downshifter 9 Training Shoes\")]]"));

Alternatives:

  1. //h2[.='Men's Downshifter 9 Training Shoes']
  2. //span[.='Men's Downshifter 9 Training Shoes']/ancestor::h2[1]
  3. //h2[./a[.='Men's Downshifter 9 Training Shoes']]
Sers
  • 12,047
  • 2
  • 12
  • 31
0

To locate the element you can use either of the following based Locator Strategies:

  • Using xpath and text():

    By.xpath("//span[text()=\"Men's Downshifter 9 Training Shoes\"]"));
    
  • Using xpath and contains():

    By.xpath("//span[@class='a-size-base-plus a-color-base a-text-normal' and contains(., 's Downshifter 9 Training Shoes')]"));
    
  • Using xpath and parent <a> tag:

    By.xpath("//a[@class='a-link-normal a-text-normal' and starts-with(@href, '/Nike-Downshifter-Running-Shoes-Anthracite/dp/')]/span[@class='a-size-base-plus a-color-base a-text-normal' and contains(., 'Downshifter 9 Training Shoes')]"));
    
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352