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