记录个人学习selenium(主要为python)第四天
通过前三天的学习, 大致掌握了浏览器的启动和基本功能,但是在实现浏览器自动化的过程中,会发现网站加载会十分耗时,导致程序总是跑得比网站快而出现 一个no such element 的错误。因此,就需要等待,等待元素的出现。
等待一般分为三种: 绝对等待(sleep),显性等待和隐形等待(selenium自带的)。当然你还可以使用其他等待module来实现。
在这里,笔者会重点解释显性等待,也推荐sleep和显性等待混合使用。
一,绝对等待
使用time模块的sleep,设置等待时间(一般比较耗时,因为需要测试合适的等待时间)
sleep(10) # 等待10秒
二,隐形等待
隐形等待,就是WebDriver在试图查找_任何_元素时在一定时间内轮询DOM。这就意味着失去灵活性。因此,不推荐使用隐形等待,除非十分适合。
driver = Firefox()
driver.implicitly_wait(10) # 隐性等待,只需在开头设置一次,之后每次试图查找任何元素时都会进行隐形等待
driver.get("http://somedomain/url_that_delays_loading")
my_dynamic_element = driver.find_element(By.ID, "myDynamicElement")
三,显性等待
显性等待, 就是允许您的代码暂停程序执行,或冻结线程,直到满足通过的 条件 , 即这个条件会以一定的频率一直被调用,等待和尝试,直至超时。
# 官网代码
from selenium.webdriver.support.ui import WebDriverWait # 也可以from selenium.webdriver.support.wait import WebDriverWait
def document_initialised(driver):
return driver.execute_script("return initialised") # 执行js语句
driver.navigate("file:///race_condition.html")
WebDriverWait(driver).until(document_initialised) # 显性等待,条件为函数执行
el = driver.find_element(By.TAG_NAME, "p")
assert el.text == "Hello from JavaScript!"
解析WebDriver类:
class WebDriverWait(object):
def __init__(self, driver, timeout, poll_frequency=POLL_FREQUENCY, ignored_exceptions=None):
'''
1. 成员变量: 从该类的初始化声明可以,可以明确知道他有那些变量,也知道它必须有driver和timeout。
'''
"""Constructor, takes a WebDriver instance and timeout in seconds.
:Args: # 担心有朋友看不懂英文,简单翻译一下
- driver - Instance of WebDriver (Ie, Firefox, Chrome or Remote) # 浏览器驱动的实例
- timeout - Number of seconds before timing out # 等待的最长时间,超过就会报超时错误
- poll_frequency - sleep interval between calls # 尝试(看看是否满足条件)的间隔,默认为0.5
By default, it is 0.5 second.
- ignored_exceptions - iterable structure of exception classes ignored during calls. # 忽视错误
By default, it contains NoSuchElementException only.
"""
'''
2. 成员函数:until 和 until_not
until(method, message="") method可以当作条件,message则为错误。函数的功能为 直到满足条件为真为止
until_not则和until 恰恰相反,功能为 直到条件为false为止
'''
'''
3. until和until_not中 method参数讨论:
调用 expected_condition 如下
from selenium.webdriver.support import expected_conditions as EC
'''
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium import webdriver
driver = webdriver.Chrome() # FireFox()
WebDriver(driver, 20, 1).untill(EC.visibility_of(driver.find_element(By.XPATH, label_xpath)))
# 显性等待, 直到能看到label为止
selenium早已帮我们归纳一些, 放在了 expected_conditions 里面
详细讲解在下述的链接里: https://seleniumhq.github.io/selenium/docs/api/py/webdriver_support/selenium.webdriver.support.expected_conditions.html?highlight=expected
浙公网安备 33010602011771号