[英]Finding href link using python selenium xpath
所以我想使用xpath從<p>標簽獲取href 。
我想使用<h1>標簽中的文本 (“ Cable Stripe Knit L / S Polo”),同時使用<p>標簽中的文本 (“ White”)在<p>標簽中找到href
。 。
注意:一件商品的顏色更多(更多的文章使用不同的<p>標簽但相同的<h1>標簽)!
HTML來源
<article>
<div class="inner-article">
<a href="/shop/tops-sweaters/ix4leuczr/a1ykz7f2b" style="height:150px;">
</a>
<h1>
<a href="/shop/tops-sweaters/ix4leuczr/a1ykz7f2b" class="name-link">Cable Stripe Knit L/S Polo
</a>
</h1>
<p>
<a href="/shop/tops-sweaters/ix4leuczr/a1ykz7f2b" class="name-link">White</a>
</p>
</div>
</article>
我已經嘗試過此代碼,但無法正常工作
specificProductColor = driver.find_element_by_xpath("//div[@class='inner-article' and contains(text(), 'White') and contains(text(), 'Cable')]/p")
driver.get(specificProductColor.get_attribute("href"))
非常感謝您的回復!
根據html來源,獲取href標簽的xpath如下所示:
specificProductColors = driver.find_elements_by_xpath("//div[@class='inner-article']//a[contains(text(), 'White') or contains(text(), 'Cable')]")
specificProductColors[0].get_attribute("href")
specificProductColors[1].get_attribute("href")
由於有2個超鏈接標記,因此您應該使用find_elements_by_xpath來返回元素列表。 在這種情況下,它將返回2個超鏈接標記,您可以使用get_attribute方法獲取其href。
我有一個工作代碼。 它不是最快的-這部分大約需要550毫秒,但它可以工作。 如果有人能簡化一下,我將非常感激:)
。
它也從產品頁面中獲取所有具有指定關鍵字(電纜)的產品,並從產品頁面中獲取具有指定顏色(白色)的所有產品。 它比較href鏈接,並將所需產品與所需顏色進行匹配。
。
還想簡化循環-如果鏈接匹配,則停止兩個循環
specificProduct = driver.find_elements_by_xpath("//div[@class='inner-article']//*[contains(text(), '"+ productKeyword[arrayCount] +"')]")
specificProductColor = driver.find_elements_by_xpath("//div[@class='inner-article']//*[contains(text(), '"+ desiredColor[arrayCount] +"')]")
for i in specificProductColor:
specProductColor = i.get_attribute("href")
for i in specificProduct:
specProduct = i.get_attribute("href")
if specProductColor == specProduct:
print(specProduct)
wantedProduct = specProduct
driver.get(wantedProduct)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.