尝试使用Python + XPath单击突出显示的文本?

时间:2018-05-25 00:02:39

标签: python python-3.x selenium

编码和Python相当新,我正在尝试使用find_element_by_xpath点击突出显示的文字"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')

HTML代码:

<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>

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

XPath有时会很快得到,因为你可以从浏览器中获取它,这就是为什么有这么多人使用它的原因,但在我看来,长期来看,学习JavaScript和CSS选择器可以在很多情况下帮助你在将来。 也可以通过选择所有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() 元素并使用纯JavaScript查找文本并将结果传递给python来完成上述操作:

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()

或者您也可以按班级选择:

id

鉴于您的元素通常由id选择id属性,这是最佳做法,因为它是最快的搜索,您应该只有一个元素id通常link_you_search = br.find_element_by_id('productTitle69507') link_you_search.click() 在翻译等情况下不会经常更改,因此在您的情况下会是:

{{1}}