我是靠谱客的博主 洁净煎饼,最近开发中收集的这篇文章主要介绍python selenium 等待元素出现_python3+selenium3自动化测试—元素等待-等待显示,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

在打开网页定位元素的时候,在网络不好或者页面卡顿的情况下会导致元素定位失败,此时不建议使用sleep()强制等待。

首先正常导入模块

1 from selenium import webdriver

2 from selenium.webdriver.support.ui import WebDriverWait

3 from selenium.webdriver.support import expected_conditions as EC

4 from selenium.webdriver.common.by import By

5 from time import sleep

上面的模块分别为:

WebDriverWait:显示等待模块(必用)

expected_conditions:预期条件类(里面包含方法可以调用,用于等待显示)

By:用于定位元素

as的作用类似于定义一个变量,即把“expected_conditions”定义为“as”,后期代码书写便捷

1 driver=webdriver.Firefox()

2

3 driver.get("http://baidu.com")

4 sleep(2)

5

6 driver.find_element_by_css_selector("#kw").send_keys("Selenium")

正常打开百度网页

1 element=WebDriverWait(driver,5,0.5).until(EC.presence_of_element_located((By.ID,'su')))

定义一个值,打开网页后等待五秒,每0.5秒请求一次,知道可以获取到ID='su'的这个元素

1 element.click()

点击按钮

全部代码如下

1 from selenium import webdriver

2 from selenium.webdriver.support.ui import WebDriverWait

3 from selenium.webdriver.support import expected_conditions as EC

4 from selenium.webdriver.common.by import By

5 from time import sleep

6

7

8 driver=webdriver.Firefox()

9

10 driver.get("http://baidu.com")

11 sleep(2)

12

13 driver.find_element_by_css_selector("#kw").send_keys("Selenium")

14

15 element=WebDriverWait(driver,5,0.5).until(EC.presence_of_element_located((By.ID,'su11')))

16

17 element.click()

18

19 sleep(3)

标签:webdriver,driver,selenium,element,sleep,selenium3,import,等待,python3

来源: https://www.cnblogs.com/HYL1003597280/p/14311124.html

最后

以上就是洁净煎饼为你收集整理的python selenium 等待元素出现_python3+selenium3自动化测试—元素等待-等待显示的全部内容,希望文章能够帮你解决python selenium 等待元素出现_python3+selenium3自动化测试—元素等待-等待显示所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(40)

评论列表共有 0 条评论

立即
投稿
返回
顶部