惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

U
Unit 42
Google DeepMind News
Google DeepMind News
Stack Overflow Blog
Stack Overflow Blog
H
Help Net Security
MongoDB | Blog
MongoDB | Blog
I
InfoQ
N
Netflix TechBlog - Medium
T
Tailwind CSS Blog
量子位
博客园 - 叶小钗
月光博客
月光博客
IT之家
IT之家
G
Google Developers Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
小众软件
小众软件
S
SegmentFault 最新的问题
Engineering at Meta
Engineering at Meta
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
aimingoo的专栏
aimingoo的专栏
云风的 BLOG
云风的 BLOG
Vercel News
Vercel News
爱范儿
爱范儿
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
宝玉的分享
宝玉的分享

博客园 - Chen.HJ

python用正则对字符串进行运算 Nginx安装和遇到过的坑 Redis安装与常用命令 Nginx、Tomcat和Redis配置文件说明 python + selenium 获取标签文本的为空解决办法 Python读取Excel Python使用paramiko的SFTP get或put整个目录 Linux系统性能监控工具nmon python+selenium个人学习笔记11-登录封装与调用 python+selenium+unittest测试框架4-邮件发送最新测试报告 python+selenium+unittest测试框架3-项目构建和发送邮件 python+selenium+unittest测试框架2-装饰器@classmethod python+selenium+unittest测试框架1-unittest单元测试框架和断言 python+selenium个人学习笔记10-调用JavaScript和截图 python+selenium个人学习笔记9-文件上传和cookie操作 python+selenium个人学习笔记8-获取信息和勾选框 python+selenium个人学习笔记7-警告框处理和下拉框选择 python+selenium个人学习笔记5-多窗口和多表单切换 python+selenium个人学习笔记4-鼠标和键盘操作
python+selenium个人学习笔记6-元素等待
Chen.HJ · 2018-03-06 · via 博客园 - Chen.HJ

元素等待

1、设置显示等待

driver.implicitly_wait(10)

示例:

from selenium import webdriver
from time import ctime
driver = webdriver.Chrome()
#设置隐式等待
driver.implicitly_wait(10)
driver.get("http://www.baidu.com")
driver.find_element_by_link_text('登录').click()
print(ctime())
driver.find_element_by_link_text("立即注册").click()
print(ctime())
driver.quit()

PS:implicitly_wait()默认参数的单位为秒,设定的时长不是一个固定的等待时间。它也不是针对页面上的某一个元素。当脚本需要定位元素时,定位到元素,继续执行脚本;如果定位不到元素,直到超出设定的时长,则抛出异常。

2、显示等待

WebDriverWait(driver, timeout, poll_frequency=0.5, ignored_exceptions=None)

driver :浏览器驱动

timeout :最长超时时间,默认以秒为单位。

poll_frequency :检测的间隔(步长)时间,默认为0.5S

ignored_exceptions :超时后的异常信息,默认情况下抛NoSuchElementException异常

示例:

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.Chrome()
driver.get("http://www.baidu.com")
#设置显示等待
element = WebDriverWait(driver, 5, 0.5).until(
                      EC.presence_of_element_located((By.ID, "kw"))
                      )
element.send_keys("chen")
driver.quit()

PS:显式等待使WebdDriver等待某个条件成立时继续执行,超出设定的时长,则抛出异常。显示等待一般配合该类的until()和until_not()方法使用。

3、强制等待

sleep,默认单位为秒(s)

示例:

#从selenium中导入webdriver模块
from selenium import webdriver
#导入time模块
from time import sleep
#打开Chrome浏览器
driver = webdriver.Chrome()
#设置等待时间
sleep(5)
#打开百度首页
driver.get("https://www.baidu.com")