Python Selenium按类和tex查找元素

2024-09-24 00:33:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试分页搜索结果:Becoming Amazon search。我得到一个'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”。


Tags: andtextdividbydriver评论element
3条回答

您试图在同一谓词中混合来自不同web元素的属性和文本节点。你应该试着把它们分开如下:

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>

因此,您希望找到一个类为pagnLinkspan,该类有一个子元素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))

相关问题 更多 >