Python:Selenium:find_elements_by_xpath最多10个

Aar*_*onk 0 python selenium python-3.x selenium-firefoxdriver selenium-webdriver

因此,我现在有一个看起来像这样的工作代码;

            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
Run Code Online (Sandbox Code Playgroud)

这一切都很好。它有60个元素。现在我只需要第一个10。如何使它只有find_elements_by_xpath10个限制?

有什么办法吗?

谢谢!

====编辑====

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

小智 5

您可以使用:

//[yourXpath]/*[position()<=10]
Run Code Online (Sandbox Code Playgroud)

就你而言

//div[contains(@class, 'dealspg_item_cell')]/*[position()<=10]
Run Code Online (Sandbox Code Playgroud)