一。等待
1.强制等待
使用方法:time.sleep()
特点:非智能等待,等待时间不好控制,多用在不同系统之间的等待时间的设置
2.隐性等待
智能等待(设置一个时间,在超时之前能够找到直接返回元素,如果超时就报错:NoSuchElementException)
特点:1.全局设置;
2.设置超时时间,超过时间报错:NoSuchElementException
3.只能等待元素
使用:
from selenium import webdriver
import time
driver=webdriver.Chrome()
#设置隐性等待时间为5秒
driver.implicitly_wait(5)
3.显性等待
特点:1.可以等待某个可以被点击
2.可以等待某个元素可见
3.等待某个窗口被打开
4.显性等待不是全局的,每次等待都要单独设置
使用(比较常用):
- presence_of_element_located(locator) 元素是否出现
- visibility_of_element_located(locator) 元素是否可见
- element_to_be_clickable(locator) 元素是否可以被点击
例子:
#显性等待
#第一设置定时器,没0.5秒获取一次,一直持续三秒中
wait=WebDriverWait(driver,3,poll_frequency=0.5)
#第二:设置满足的条件
#设置locator条件,以xpath方式,后面式表达式
locator=(‘xpath‘,‘//*[text()="ke.qq.com/"]‘)
#等待该元素为可点击状态
element_tengxun=wait.until(expected_conditions.element_to_be_clickable(locator=locator))
driver.get("http://www.baidu.com")
二。切换
1.窗口切换
#窗口切换
#driver.window_handles - -获取所有句柄;driver.switch_to.window选择窗口
driver.switch_to.window(driver.window_handles[-1])
#获取当前窗口的url信息
print(driver.current_url)
运行结果:
原文:https://www.cnblogs.com/newsss/p/13310756.html