0

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

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

目前它正在访问主列表页面并在单击第一个链接之前直接单击“共享”。也许我想多了,因为我认为 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
4

1 回答 1

0

您应该使用 代替 sleep ,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
    
于 2020-11-03T21:24:22.247 回答