簡體   English   中英

Python Selenium - 按類和文本查找元素

[英]Python Selenium - Find element by class and text

我正試圖通過搜索結果進行分頁: 成為亞馬遜搜索 我得到'NoSuchElementException'..'Unable to locate element: < insert xpath here >

這是html:

<div id="pagn" class="pagnHy">
    <span class="pagnLink">
        <a href="/s/ref=sr_pg_2?rh=...">2</a>
    </span>
</div>

這是我嘗試過的xpath:

driver.find_element_by_xpath('//*[@id="pagn" and @class="pagnLink" and text()="2"]')

driver.find_element_by_xpath('//div[@id="pagn" and @class="pagnLink" and text()="2"]')

driver.find_element_by_xpath("//*[@id='pagn' and @class='pagnLink' and text()[contains(.,'2')]]")

driver.find_element_by_xpath("//span[@class='pagnLink' and text()='2']")

driver.find_element_by_xpath("//div[@class='pagnLink' and text()='2']")

如果我只使用find_element_by_link_text(...)那么有時會選擇錯誤的鏈接。 例如,如果評論的數量等於我正在尋找的頁碼(在這種情況下,2),那么它將選擇具有2個評論的產品,而不是頁碼“2”。

您嘗試在同一謂詞中混合來自不同WebElements的屬性和文本節點。 你應該嘗試將它們分開如下:

driver.find_element_by_xpath('//div[@id="pagn"]/span[@class="pagnLink"]/a[text()="2"]')

當我查看標記時,我看到以下內容:

<span class="pagnLink">
    <a href="/s/ref=sr_pg_2?rh=...">2</a>
</span>

所以,你想找到一個span帶班pagnLink有一個孩子a與文本元素2 ,或:

'//*[@class="pagnLink"]/a[text()="2"]'

有時候,采取中間步驟並首先獲得包含結果的元素可能會更好。 之后你只需在這個元素中搜索。 這樣做可以簡化搜索條件。

from selenium import webdriver

url = 'https://www.amazon.com/s/ref=nb_sb_noss_2?url=search-alias%3Daps&fieldkeywords=becoming&rh=i%3Aaps%2Ck%3Abecoming'
driver = webdriver.Firefox()
resp = driver.get(url)
results_list_object = driver.find_element_by_id('s-results-list-atf')
results = results_list_object.find_elements_by_css_selector('li[id*="result"]')

for number, article in enumerate(results):
    print(">> article %d : %s \n" % (number, article.text))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM