编码和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>
答案 0 :(得分:1)
br.find_element_by_xpath("//h2[text()='Snoring Chin Strap by TheFamilyMarket']");
答案 1 :(得分:0)
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}}