簡體   English   中英

如何讓 selenium 等到找到元素而不是使用 time.sleep()

[英]How to make selenium wait until the element is found instead of using time.sleep()

基本上,我正在構建一個小腳本來自動化一些基本的東西。 我一直在使用 time.sleep() 讓軟件稍等片刻,直到所有內容都加載完畢,但有更好的方法嗎?

我希望腳本本身等待盡可能長的時間,以使事情變得更快、更干凈。

from selenium import webdriver

from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import Select
import time
from tkinter import *


def cs_update():

    PATH = "C:\Program Files (x86)\chromedriver.exe"
    options = Options()
    options.headless = True



    driver = webdriver.Chrome(PATH,options = options) 
    driver.set_window_size(1920,1080)
    driver.minimize_window()

    user_email = e.get()
    user_password = e2.get()

    driver.get("https://www.compraensanjuan.com")
    time.sleep(3)


    link = driver.find_element_by_link_text("Mi cuenta")

    link.click()
    time.sleep(3)

    email = driver.find_element_by_name("email")

    email.send_keys(user_email)

    print("I sent the keys")

這就是您可以使用ExplicitWait的方式

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

driver.get("https://www.compraensanjuan.com")

timeout = 20 # set seconds to wait until TimeOutException raised
link = WebDriverWait(driver, timeout).until(EC.element_to_be_clickable((By.LINK_TEXT, "Mi cuenta")))

link.click()

email = WebDriverWait(driver, timeout).until(EC.presence_of_element_located((By.NAME, "email")))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM