Python Selenium - 按类和文本查找元素 [英] Python Selenium - Find element by class and text

查看:34
本文介绍了Python Selenium - 按类和文本查找元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对搜索结果进行分页:成为亚马逊搜索.我得到一个 'NoSuchElementException'..'Unable to locate element: <在此处插入 xpath >

这是html:

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

以下是我尝试过的 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"]')

I'm trying to paginate through the results of this search: Becoming Amazon search. I get a 'NoSuchElementException'..'Unable to locate element: < insert xpath here >

Here is the html:

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

Here are the xpaths I've tried:

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']")

If I just use find_element_by_link_text(...) then sometimes the wrong link will be selected. For example, if the number of reviews is equal to the page number I'm looking for (in this case, 2), then it will select the product with 2 reviews, instead of the page number '2'.

解决方案

You're trying to mix attributes and text nodes from different WebElements in the same predicate. You should try to separate them as below:

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

这篇关于Python Selenium - 按类和文本查找元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆