使用 Python 和 Selenium 时在 for 循环中按顺序执行步骤

Making steps in a for loop sequential when using Python and Selenium

我正在尝试遍历网页上的 link 列表,使用 selenium 单击每个列表,然后从每个页面复制一个 tinylink 最后返回到主列表页。到目前为止它将访问该页面,但我正在努力获得

的顺序

点击link->加载页面->点击'share'->点击'copy'

目前它正在访问主列表页面并直接单击 'share',然后再单击第一个 link。也许我想太多了,因为我认为 sleep(1) 会在那里切断程序,直到下一步。请帮忙!

#below accesses each link, opens the tinylink, and copies it
powerforms = driver.find_element_by_xpath("//*[@id='main-content']/ul")
links = powerforms.find_elements_by_tag_name("li")

for link in links:
    link.click()
    sleep(1)

    #clicks 'Share' button to open popout
    share = driver.find_element_by_id("shareContentLink")
    share.click()
    sleep(1)

    #clicks 'Copy' button to copy the tinylink to the clipboard
    copy = driver.find_element_by_id("share-link-copy-button")
    copy.click()
    sleep(1)
    break

您应该使用 WebDriverWait 而不是休眠,以确保该元素出现在页面上、已加载并且可以交互。睡眠不考虑您的网速等

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException

driver = webdriver.Firefox()
driver.get(url)
max_wait_time = 10 #seconds

powerforms = driver.find_element_by_xpath("//*[@id='main-content']/ul")
links = powerforms.find_elements_by_tag_name("li")

for link in links:
    try:
        link = WebDriverWait(driver, max_wait_time).until(EC.presence_of_element_located(link))
        link.click()

        # clicks 'Share' button to open popout
        share = WebDriverWait(driver, max_wait_time).until(EC.presence_of_element_located((By.ID, 'shareContentLink')))
        share.click()
        # sleep(1)

        # clicks 'Copy' button to copy the tinylink to the clipboard
        copy = WebDriverWait(driver, max_wait_time).until(EC.presence_of_element_located((By.ID, 'share-link-copy-button')))
        copy.click()
        # sleep(1)

    except TimeoutException:
        print("Couldn't load element")
        continue