web自动化测试中,用的最多的几种验证信息是title, current_url, text。title:获取当前页面标题;current_url:获取当前页面url;text: 获取当前页面文本信息。
from selenium import webdriver import time driver = webdriver.Firefox() driver.get("https://www.baidu.com") text = driver.find_element_by_id("s-bottom-layer-right").text print(text) title = driver.title print(title)
now_url = driver.current_url print(now_url) """ output:©2020 Baidu (京)-经营性-2017-0020京公网安备11000002000001号京ICP证030173号 百度一下,你就知道 https://www.baidu.com/ """
from selenium import webdriver import time driver = webdriver.Firefox() driver.get("https://www.baidu.com") driver.find_element_by_id("kw").send_keys("python") driver.find_element_by_id("su").click() time.sleep(2) title = driver.title now_url = driver.current_url nums = driver.find_element_by_class_name("nums_text").text print(title) print(now_url) print(nums)
2、设置元素等待:显示等待和隐士等待。
显示等待:webdriver等待某个条件成立则继续执行,否则在到达最大等待时长时抛出异常。
语法:WebDriverWait(driver, timeout, poll_frequency=0.5, ingored_exceptions=None)
driver: 浏览器驱动;timeout: 最长超时时间,默认以秒为单位;poll_frequency: 检测的时间间隔,默认0.5s;ingored_exceptions=None: 超时后异常信息。
WebDriverWait() 一般与until() 或until_not()方法配合使用:until(method, message=" "); until_not(method, message=" ")
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.Firefox() driver.get("http://www.baidu.com") element = WebDriverWait(driver,5,0.5).until( EC.visibility_of_element_located((By.ID,"kw"))) element.send_keys("python") driver.quit()
隐式等待:implicitly_wait(): 参数是时间,单位 s。
from selenium import webdriver from selenium.common.exceptions import NoSuchElementException from time import ctime driver = webdriver.Chrome() driver.implicitly_wait(10) driver.get("https://www.baidu.com") try: print(ctime()) driver.find_element_by_id("kw2").send_keys("python") except NoSuchElementException as e: print(e) finally: print(ctime()) driver.quit()