【问题标题】:Python Selenium - Find element by class and textPython Selenium - 按类和文本查找元素
【发布时间】:2018-12-03 20:31:17
【问题描述】:

我正在尝试对搜索结果进行分页: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”。

【问题讨论】:

    标签: python selenium xpath


    【解决方案1】:

    您试图在同一个谓词中混合来自不同 WebElement 的属性和文本节点。您应该尝试将它们分开如下:

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

    【讨论】:

    • 这行得通!这个例子中的属性和文本节点是什么?你有什么好的资源来学习这个吗?
    • 本例中的属性是idclass:出现在inside 标签的节点,例如&lt;tag_name attr_1="foo" attr_2="bar"&gt;...&lt;/tag_name&gt;。在 XPath 中,您可以将属性称为 @attr_nameattribute:attr_name。在您的情况下,文本节点是 "2" - 值 outside 标记,例如&lt;tag_name&gt;parent_text_1&lt;child_tag&gt;child_text&lt;/child_tag&gt;parent_text_2&lt;/tag_name&gt;。您可以使用this cheat sheet 创建格式良好的 XPath 表达式(或 CSS 选择器)
    【解决方案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))
    

    【讨论】:

      【解决方案3】:

      当我查看标记时,我看到以下内容:

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

      所以你想找到一个 spanpagnLink 有一个子 a 元素和文本 2,或者:

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

      【讨论】:

        猜你喜欢
        • 2019-11-18
        • 2012-08-14
        • 2012-08-14
        • 2015-07-12
        • 2018-10-12
        • 2021-03-05
        • 2023-01-03
        • 2016-06-08
        • 2014-09-19
        相关资源
        最近更新 更多