【问题标题】:Python: Selenium: find_elements_by_xpath max 10Python:硒:find_elements_by_xpath 最大 10
【发布时间】:2019-08-05 07:56:57
【问题描述】:

所以,我现在有一段看起来像这样的工作代码;

if browser.find_elements_by_xpath("//div[contains(@class, 'dealspg_item_cell')]"):
    snipes = browser.find_elements_by_xpath("//div[contains(@class, 'dealspg_item_cell')]")
else:
    print "Cant find snipes.. Retrying..."
    browser.get("https://www.rolimons.com/deals")
    time.sleep(2)
    print "Reloaded browser... Retrying..."
    if browser.find_elements_by_xpath("//div[contains(@class, 'dealspg_item_cell')]"):
        snipes = browser.find_elements_by_xpath("//div[contains(@class, 'dealspg_item_cell')]")
    else:
        print "Shutting down engine..."
        browser.quit()
        checking = False
        print "Restarting script..."
        break

这一切都很好。它有 60 个元素。现在我只需要前 10 个。我怎样才能让它只有 find_elements_by_xpath 限制为 10?

有什么办法吗?

谢谢!

==== 编辑 ====

此代码目前需要 4 秒。我希望通过将最大值设置为 10 来减少此时间。

【问题讨论】:

    标签: python python-3.x selenium selenium-webdriver selenium-firefoxdriver


    【解决方案1】:

    你可以使用:

    //[yourXpath]/*[position()<=10]
    

    在你的情况下

    //div[contains(@class, 'dealspg_item_cell')]/*[position()<=10]
    

    【讨论】:

    • 谢谢!我在谷歌上找不到任何关于此的内容。所以我只是搜索它。
    【解决方案2】:

    虽然使用 xpath 是一个很好的答案。您还可以根据性能分别参考 css 选择器。就我个人而言,我遇到了这样的问题,即 xpath 不起作用但 CSS 选择器是

    div.dealspg_item_cell:nth-child(-1n+10)
    

    解释nth-child(-1n+10)

    +10 在这里表示节点位置,我们要从中挑选元素 -1n第10个节点之前的所有节点

    假设总共有 11 个元素,那么选择将类似于:

    另一个例子是nth-child(1n+10),表示第10个节点之后的所有其他节点

    您可以通过here了解更多信息

    【讨论】:

      猜你喜欢
      • 2019-11-23
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-15
      • 1970-01-01
      • 1970-01-01
      • 2022-11-14
      相关资源
      最近更新 更多