Kas Dar
Kas Dar

Reputation: 21

Trying to use Python + XPath to click the highlighted text?

Fairly new to coding and Python, I'm trying to use find_element_by_xpath to click the text highlighted text "Snoring Chin Strap by TheFamilyMarket".

    time.sleep(2)

    #btn = br.find_element_by_name("#Anti Snoring Chin Strap Kit")
    # btn = br.find_element_by_link_text('Snoring Chin Strap')

The HTML code:

<div class="tableD">
   <div class="productDiv" id="productDiv69507">
      <h2 class="productTitle" id="productTitle69507" onclick="goToProduct(7)">Snoring Chin Strap by TheFamilyMarket</h2>
      <img class="productImage" src="https://images-na.ssl-images-amazon.com/images/I/516fC3JruqL.jpg" onclick="goToProduct(7)">
      <hr>
      <h4 class="normalPrice" id="normalPrice7" onclick="goToProduct(7)">Normally: <span class="currency">$  </span>19.99</h4>
      <h4 class="promoPrice" style="margin:2.5px auto;" id="promoPrice69507" onclick="goToProduct(7)">Your Amazon Price: <span class="currency">$  </span>1.99</h4>
      <h3>Your Total:  <span class="currency">$  </span>1.99</h3>
      <p class="clickToViewP" id="cToVP69507" onclick="goToProduct(7)">Click to view and purchase!</p>
   </div>
</div>

Upvotes: 1

Views: 219

Answers (2)

yong
yong

Reputation: 13722

br.find_element_by_xpath("//h2[text()='Snoring Chin Strap by TheFamilyMarket']");

Upvotes: 1

Eduard Florinescu
Eduard Florinescu

Reputation: 17541

XPath is sometimes fast to get because you can get it from the browser, and that's why so many people use it, but in my opinion for long term, learning JavaScript and CSS selectors can help you in many instances in the future. The above can be done also by selecting all the h2 elements and looking for text using plain JavaScript and passing the result to python:

link_you_search = br.execute_script('''
links= document.querySelectorAll("h2");
for (link of links) if (link.textContent.includes("Chin Strap")) return link;
 ''')
link_you_search.click()

or alternatively you can select by class:

link_you_search = br.execute_script('''
links= document.querySelectorAll(".productDiv");
for (link of links) if (link.textContent.includes("Chin Strap")) return link;
 ''')
link_you_search.click()

given that your element has an id attribute usually selecting by id it is best practice since it is the fastest search and you should only have only one element with that id and usually ids don't change so often in case of translation etc, so in your case it would be:

link_you_search = br.find_element_by_id('productTitle69507')
link_you_search.click()

Upvotes: 0

Related Questions