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

2024-10-03 21:24:50 发布

您现在位置:Python中文网/ 问答频道 /正文

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

单击链接->;加载页面->;单击“共享”->;单击“复制”

目前,它正在访问主列表页面,直接点击“共享”,然后点击第一个链接。也许我想得太多了,因为我认为睡眠(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

Tags: thegtid列表by链接driverlink
1条回答
网友
1楼 · 发布于 2024-10-03 21:24:50

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

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
    

相关问题 更多 >