Python3关于selenium的强制等待、隐式等待和显式等待(附上EC的主要方法)

强制等待

from selenium import webdriver
import time
driver = webdriver.Chrome()
driver.get('https://www.baidu.com')
print(driver.current_url)
time.sleep(3)
driver.quit()
  • 分析:强制等待,死板且不灵活,若等待时间过长则严重影响程序执行速度

隐式等待

from selenium import webdriver
import time
driver = webdriver.Chrome()
driver.get('https://www.baidu.com')
print(driver.current_url)
driver.implicitly_wait(30)
driver.quit()
  • 分析:隐形等待是设置了一个最长等待时间,如果在规定时间内网页加载完成,则执行下一步,否则一直等到时间截止,然后执行下一步。注意这里有一个弊端,那就是程序会一直等待整个页面加载完成,也就是一般情况下你看到浏览器标签栏那个小圈不再转,才会执行下一步,但有时候页面想要的元素早就在加载完成了,但是因为个别js之类的东西特别慢,我仍得等到页面全部完成才能执行下一步,我想等我要的元素出来之后就下一步怎么办?有办法,这就要看selenium提供的另一种等待方式——显性等待wait了。

需要特别说明的是:隐性等待对整个driver的周期都起作用,所以只要设置一次即可,我曾看到有人把隐性等待当成了sleep在用,走哪儿都来一下

显性等待

WebDriverWait为显型等待,配合until()和until_not()方法,就能够根据EC而进行灵活地等待了。它主要的意思就是:程序每隔xx秒看一眼,如果条件成立了,则执行下一步,否则继续等待,直到超过设置的最长时间,然后抛出TimeoutException。

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

driver = webdriver.Chrome()
# 第二个参数30,表示等待的最长时间,超过30秒则抛出TimeoutException
# 第三个参数0.2,表示0.2秒去检查一次
wait = WebDriverWait(driver, 30, 0.2)
driver.get('https://www.baidu.com')
wait.until(EC.presence_of_element_located((By.ID, "lg")))
print(driver.current_url)
driver.quit()
until

method: 在等待期间,每隔一段时间(__init__中的poll_frequency)调用这个传入的方法,直到返回值不是False
message: 如果超时,抛出TimeoutException,将message传入异常

until_not

与until相反,until是当某元素出现或什么条件成立则继续执行, until_not是当某元素消失或什么条件不成立则继续执行,参数也相同,不再赘述。

expected_conditions

expected_conditions是selenium的一个模块,其中包含一系列可用于判断的条件:

selenium.webdriver.support.expected_conditions(模块)

以下两个条件类验证title,验证传入的参数title是否等于或包含于driver.title
title_is
title_contains

以下两个条件验证元素是否出现,传入的参数都是元组类型的locator,如(By.ID, ‘kw’)
顾名思义,一个只要一个符合条件的元素加载出来就通过;另一个必须所有符合条件的元素都加载出来才行
presence_of_element_located
presence_of_all_elements_located

以下三个条件验证元素是否可见,前两个传入参数是元组类型的locator,第三个传入WebElement
第一个和第三个其实质是一样的
visibility_of_element_located
invisibility_of_element_located
visibility_of

以下两个条件判断某段文本是否出现在某元素中,一个判断元素的text,一个判断元素的value
text_to_be_present_in_element
text_to_be_present_in_element_value

以下条件判断frame是否可切入,可传入locator元组或者直接传入定位方式:id、name、index或WebElement
frame_to_be_available_and_switch_to_it

以下条件判断是否有alert出现
alert_is_present

以下条件判断元素是否可点击,传入locator
element_to_be_clickable

以下四个条件判断元素是否被选中,第一个条件传入WebElement对象,第二个传入locator元组
第三个传入WebElement对象以及状态,相等返回True,否则返回False
第四个传入locator以及状态,相等返回True,否则返回False
element_to_be_selected
element_located_to_be_selected
element_selection_state_to_be
element_located_selection_state_to_be

最后一个条件判断一个元素是否仍在DOM中,传入WebElement对象,可以判断页面是否刷新了
staleness_of

猜你喜欢

转载自blog.csdn.net/weixin_39020133/article/details/106520127