停止程序,直到找到一个元素[Selenium,Python]

问题描述 投票:0回答:1
import pyautogui
import selenium
import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

你好!因此,我已经能够在硒Solving is in process... http://prntscr.com/pib0pf中进行检测,然后,如果元素处于活动状态,则在继续其余代码之前,将激活time.sleep()。在解决问题之前给验证码一些时间。但问题是我改变了主意,认为如果找到一种方法对元素进行硒检查并且如果该元素尚不可用,则应该执行time.sleep(),这实际上会更好。我想要这个,因为如果在给定时间内未解决验证码,第一个想法就会出错。但是有了第二个想法,Selenium将自动检查给定的Element是否处于活动状态,如果没有激活,则应在脚本的其余部分执行之前将30秒添加到脚本中。

#~ Continuing code

time.sleep(3)
print("Form filled!")
time.sleep(10)


if driver.find_element_by_xpath("//div[@class='antigate_solver recaptcha in_process']"):
    print("Waiting 60 seconds...\n")
    time.sleep(60)

if driver.find_element_by_xpath("//div[@class='antigate_solver recaptcha solved']"):
    time.sleep(1.5)
    print("Captcha Solved...")

driver.find_element_by_xpath('/html[1]/body[1]/main[1]/div[1]/div[2]/form[1]/small[1]/div[1]/label[1]/input[1]').click()
print("Submitting...")
time.sleep(1.5)
driver.find_element_by_xpath('/html[1]/body[1]/main[1]/div[1]/div[2]/form[1]/div[12]/button[1]').click()
python selenium selenium-webdriver
1个回答
1
投票

明确等待

显式等待是您定义的代码,用于在继续执行代码之前等待特定条件发生。极端的情况是time.sleep(),它将条件设置为要等待的确切时间段。提供了一些方便的方法,可以帮助您编写仅等待所需时间的代码。 WebDriverWait与ExpectedCondition结合是可以实现此目的的一种方法。

EXP:


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

driver = webdriver.Firefox()
driver.get("http://somedomain/url_that_delays_loading")
try:
    element = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.ID, "myDynamicElement"))
    )
finally:
    driver.quit()       

此方法最多等待10秒,然后抛出TimeoutException,除非它发现要在10秒内返回的元素。默认情况下,WebDriverWait每500毫秒调用ExpectedCondition,直到成功返回。成功返回的条件是ExpectedCondition类型为Boolean返回true,否则为所有其他ExpectedCondition类型的返回值。]

来源:https://selenium-python.readthedocs.io/waits.html

© www.soinside.com 2019 - 2024. All rights reserved.