for 循环 运行s 只有一次。我需要在 selenium 网络驱动程序中 运行 多达 42 次

For loop runs only one time. I need to run up-to 42 times in selenium web-driver

我正在尝试使用 for 循环获取 web-table 数据。 table 分页最多为 42。这里是我的代码:

driver.get()
#identification and Locators
stack = driver.find_elements_by_xpath("//*[@id='container']/div/div[4]/table/tbody/tr/td[10]/div/ul/li")
quant = driver.find_elements_by_xpath("//*[@class='admin__data-grid-wrap']/table/tbody/tr/td[7]/div")
link = driver.find_elements_by_xpath("//*[@class='admin__data-grid-wrap']/table/tbody/tr/td[15]/a")
#Start a procedure
for i in driver.find_elements_by_xpath("//*[@id='container']/div/div[2]/div[2]/div[2]/div/div[2]/div/div[2]/button[2]"):
    for steck,quanty,links in zip(stack,quant,link):
        stuck = steck.text
        quantity = quanty.text
        linkes = links.get_attribute("href")
        if stuck != 'No manage stock':
            word = "Default Stock: "
            stock = stuck.replace(word, '')
            stocks = int(stock)
            quanties = int(float(quantity))
            if stocks < 0:
                print(stocks,quanties,linkes)
                stacks = abs(stocks)
                total = stacks+quanties+1
                print(total)
    i.click()
    driver.implicitly_wait(10)
    print("Next Page")

此代码从第 1 页获取数据。单击下一页后。第二个 for 循环没有从 web-table.

获取第二页数据

很可能您的查询 driver.find_elements_by_xpath("//*[@id='container']/div/div[2]/div[2]/div[2]/div/div[2]/div/div[2]/button[2]") 只有 returns 一个元素(转到下一页的实际按钮)所以我想您应该读取页码并将其用于外循环(或者至少,您可能必须重新绑定代表可点击按钮的 HTML 元素上的选择,因为它可能会在加载 table 的新页面时发生变化):

driver.get()

# Read the number of page and store it as an integer
nb_pages = int(driver.find_element_by_id('someId').text)

# Repeat your code (and rebind your selections, notably the one
# on the button to go to the next page) on each page of the table
for page in nb_pages:
    # lines below are adapted from your code, I notably removed you first loop
    stack = driver.find_elements_by_xpath("//*[@id='container']/div/div[4]/table/tbody/tr/td[10]/div/ul/li")
    quant = driver.find_elements_by_xpath("//*[@class='admin__data-grid-wrap']/table/tbody/tr/td[7]/div")
    link = driver.find_elements_by_xpath("//*[@class='admin__data-grid-wrap']/table/tbody/tr/td[15]/a")

    # loop removed here (i also splited the string for readability
    # (but it don't change the actual string value)
    i = driver.find_elements_by_xpath(
        "//*[@id='container']/div/div[2]/div[2]/div[2]"
        "/div/div[2]/div/div[2]/button[2]")[0]
    for steck, quanty, links in zip(stack, quant, link):
        # your logic ...
        # ...
    # Load the next page:
    i.click()

如果您看不懂页数,您也可以使用 while 循环并在找不到加载下一页的按钮时退出它,例如:

while True:
    i = driver.find_elements_by_xpath(
        "//*[@id='container']/div/div[2]/div[2]/div[2]"
        "/div/div[2]/div/div[2]/button[2]")
    if not i:
        break
    i = i[0]
    # the rest of your logic
    # ...

    i.click()

这只是一个猜测(因为我们没有您尝试使用的页面的示例 HTML 代码/table 结构)。