4. 弹窗
4.1 警告弹窗+确认弹窗
弹窗是在页面是找不到任何元素的,这种情况怎么处理?使用selenium提供的Alert接口。
alert = driver.switchTo.alert
# 确认
alert.accept()
# 取消
alert.dismiss()
因为
import time
import datetime
from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.common.by import By
from webdriver_manager.chrome import ChromeDriverManager
# 1.打开浏览器
chrome_driver_path = r"D:\Program Files\Python39\Scripts\chromedriver.exe"
# 1.打开浏览器
driver = webdriver.Chrome(service=ChromeService(executable_path=chrome_driver_path))
# 弹窗
driver.get("对应的网页url")
# 点击调起弹窗
driver.find_element(By.CSS_SELECTOR, "#tooltip").click() # 点击 id="tooltip" 的元素,也就弹窗,这个值要根据弹窗来改
# 切换到弹窗
alert = driver.switch_to.alert
# 点击确认按钮
alert.accept()
# 或者点击取消按钮
# alert.dismiss()
# 弹窗关闭后才能执行下面的代码
driver.find_element(By.CSS_SELECTOR, "#tooltip").click()
# 5、关闭浏览器
driver.quit()
4.2 提示弹窗
alert = driver.switchTo.alert
alert.send_keys("hello")
alert.accept()
alert.dismiss()
import time
import datetime
from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.common.by import By
from webdriver_manager.chrome import ChromeDriverManager
# 1.打开浏览器
chrome_driver_path = r"D:\Program Files\Python39\Scripts\chromedriver.exe"
# 1.打开浏览器
driver = webdriver.Chrome(service=ChromeService(executable_path=chrome_driver_path))
# 弹窗
driver.get("对应的网页url")
# 点击调起弹窗
driver.find_element(By.CSS_SELECTOR, "#tooltip").click() # 点击 id="tooltip" 的元素,也就弹窗,这个值要根据弹窗来改
# 切换到弹窗
alert = driver.switch_to.alert
# 输入文本
alert.send_keys("hello")
# 点击确认按钮
alert.accept()
# 或者点击取消按钮
# alert.dismiss()
# 弹窗关闭后才能执行下面的代码
driver.find_element(By.CSS_SELECTOR, "#tooltip").click()
# 5、关闭浏览器
driver.quit()
5. 等待
通常代码执行的速度比页面渲染的速度要快,如果避免因为渲染过慢出现的自动化误报的问题呢?可以使用selenium中提供的三种等待方法:
5.1 强制等待
time.sleep()
优点:使用简单,调试的时候比较有效
缺点:影响运行效率,浪费大量的时间
有转义字符\
,就加一个\
import time
import datetime
from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.common.by import By
from webdriver_manager.chrome import ChromeDriverManager
# 1.打开浏览器
chrome_driver_path = r"D:\Program Files\Python39\Scripts\chromedriver.exe"
# 1.打开浏览器
driver = webdriver.Chrome(service=ChromeService(executable_path=chrome_driver_path))
driver.get("https://www.baidu.com")
driver.find_element(By.CSS_SELECTOR, "#kw").send_keys("迪丽热巴")
driver.find_element(By.CSS_SELECTOR, "#su").click()
driver.find_element(By.CSS_SELECTOR, "#\\31 > div > div > div > div > div > div.new-tag_4ozgi.new-text-link_3k9GD > div > div.flex-wrapper-top_3ucFS > div.flex-col-left_3trtY.baike-wrapper_6AORN.cu-pt-xs-lg.baike-wrapper-pc_26R04.cu-pt-xl.baike-wrapper-left-pc_5eYY8.cos-space-pb-sm > div > div > p > span:nth-child(1) > span")
# 5、关闭浏览器
driver.quit()
打印:
"D:\Program Files\Python39\python.exe" D:/code/python/测试/_5test.py
Traceback (most recent call last):
File "D:\code\python\测试\_5test.py", line 17, in <module>
driver.find_element(By.CSS_SELECTOR, "#\\31 > div > div > div > div > div > div.new-tag_4ozgi.new-text-link_3k9GD > div > div.flex-wrapper-top_3ucFS > div.flex-col-left_3trtY.baike-wrapper_6AORN.cu-pt-xs-lg.baike-wrapper-pc_26R04.cu-pt-xl.baike-wrapper-left-pc_5eYY8.cos-space-pb-sm > div > div > p > span:nth-child(1) > span")
File "D:\Program Files\Python39\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 1238, in find_element
return self.execute(Command.FIND_ELEMENT, {
File "D:\Program Files\Python39\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 418, in execute
self.error_handler.check_response(response)
File "D:\Program Files\Python39\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 243, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"#\31 > div > div > div > div > div > div.new-tag_4ozgi.new-text-link_3k9GD > div > div.flex-wrapper-top_3ucFS > div.flex-col-left_3trtY.baike-wrapper_6AORN.cu-pt-xs-lg.baike-wrapper-pc_26R04.cu-pt-xl.baike-wrapper-left-pc_5eYY8.cos-space-pb-sm > div > div > p > span:nth-child(1) > span"}
(Session info: chrome=138.0.7204.97)
Stacktrace:
GetHandleVerifier [0x0x7ff620ae6f95+76917]
GetHandleVerifier [0x0x7ff620ae6ff0+77008]
(No symbol) [0x0x7ff620899dea]
(No symbol) [0x0x7ff6208f0256]
(No symbol) [0x0x7ff6208f050c]
(No symbol) [0x0x7ff620943887]
(No symbol) [0x0x7ff6209184af]
(No symbol) [0x0x7ff62094065c]
(No symbol) [0x0x7ff620918243]
(No symbol) [0x0x7ff6208e1431]
(No symbol) [0x0x7ff6208e21c3]
GetHandleVerifier [0x0x7ff620dbd2cd+3051437]
GetHandleVerifier [0x0x7ff620db7923+3028483]
GetHandleVerifier [0x0x7ff620dd58bd+3151261]
GetHandleVerifier [0x0x7ff620b0185e+185662]
GetHandleVerifier [0x0x7ff620b0971f+218111]
GetHandleVerifier [0x0x7ff620aefb14+112628]
GetHandleVerifier [0x0x7ff620aefcc9+113065]
GetHandleVerifier [0x0x7ff620ad6c98+10616]
BaseThreadInitThunk [0x0x7ffd8a09259d+29]
RtlUserThreadStart [0x0x7ffd8bd4af78+40]
进程已结束,退出代码1
但是添加一行time.sleep(2)
就可以了
import time
import datetime
from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.common.by import By
from webdriver_manager.chrome import ChromeDriverManager
# 1.打开浏览器
chrome_driver_path = r"D:\Program Files\Python39\Scripts\chromedriver.exe"
# 1.打开浏览器
driver = webdriver.Chrome(service=ChromeService(executable_path=chrome_driver_path))
driver.get("https://www.baidu.com")
driver.find_element(By.CSS_SELECTOR, "#kw").send_keys("迪丽热巴")
driver.find_element(By.CSS_SELECTOR, "#su").click()
time.sleep(2)
driver.find_element(By.CSS_SELECTOR, "#\\31 > div > div > div > div > div > div.new-tag_4ozgi.new-text-link_3k9GD > div > div.flex-wrapper-top_3ucFS > div.flex-col-left_3trtY.baike-wrapper_6AORN.cu-pt-xs-lg.baike-wrapper-pc_26R04.cu-pt-xl.baike-wrapper-left-pc_5eYY8.cos-space-pb-sm > div > div > p > span:nth-child(1) > span")
# 5、关闭浏览器
driver.quit()
这是因为代码执行的速度比页面渲染的速度要快。
1个或数量较少的测试脚本时,添加强制等待消耗的时间不过数秒。
实际在工作中,业务场景比较复杂时,要添加的自动化脚本非常多,通常来说自动化测试脚本数量可达到上百200个脚本,每个脚本添加若干个等待时间,假设平均等待时间为6秒。
200*6=1200s大约20min,这个时间在程序运行时间里算是非常久的,而实际可接受的自动化运行时间为几秒或者几分钟之内。
5.2 隐式等待
隐式等待是一种智能等待,他可以规定在查找元素时,在指定时间内不断查找元素。如果找到则代码继续执行,直到超时没找到元素才会报错。
implicitly_wait() 参数:秒
#隐式等待5秒
driver.implicitly_wait(5)
import time
import datetime
from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.common.by import By
from webdriver_manager.chrome import ChromeDriverManager
# 1.打开浏览器
chrome_driver_path = r"D:\Program Files\Python39\Scripts\chromedriver.exe"
# 1.打开浏览器
driver = webdriver.Chrome(service=ChromeService(executable_path=chrome_driver_path))
driver.get("https://www.baidu.com")
# 隐式等待3秒
driver.implicitly_wait(3)
driver.find_element(By.CSS_SELECTOR, "#kw").send_keys("迪丽热巴")
driver.find_element(By.CSS_SELECTOR, "#su").click()
driver.find_element(By.CSS_SELECTOR, "#\\31 > div > div > div > div > div > div.new-tag_4ozgi.new-text-link_3k9GD > div > div.flex-wrapper-top_3ucFS > div.flex-col-left_3trtY.baike-wrapper_6AORN.cu-pt-xs-lg.baike-wrapper-pc_26R04.cu-pt-xl.baike-wrapper-left-pc_5eYY8.cos-space-pb-sm > div > div > p > span:nth-child(1) > span")
# 5、关闭浏览器
driver.quit()
隐式等待作用域是整个脚本的所有元素。即只要
driver
对象没有被释放掉(driver.quit()
),隐式等待就一直生效。后面不管几次点击都会触发隐式等待。优点:智能等待,作用于全局
不过如果定位的元素不存在,就会等待3s
后报错。
5.3 显示等待
显示等待也是一种智能等待,在指定超时时间范围内只要满足操作的条件就会继续执行后续代码
WebDriverWait(driver,sec).until(functions)
# driver:驱动对象
# sec:等待多少秒
# .until(functions):满足条件
functions :涉及到selenium.support.ui.ExpectedConditions包下的 ExpectedConditions类
ExpectedConditions
下涉及到的方法:https://www.selenium.dev/selenium/docs/api/py/webdriver_support/selenium.webdriver.support.expected_conditions.html
from selenium.webdriver.support import expected_conditions as EC # as EC 是给了一个别名
wait = WebDriverWait(driver,2)
wait.until(EC.invisibility_of_element((By.XPATH,'//*[@id="2"]/div/div/div[3]/div[1]/div[1]/div')))
import time
import datetime
from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC # as EC 是给了一个别名
from selenium.webdriver.support.wait import WebDriverWait
from webdriver_manager.chrome import ChromeDriverManager
# 1.打开浏览器
chrome_driver_path = r"D:\Program Files\Python39\Scripts\chromedriver.exe"
# 1.打开浏览器
driver = webdriver.Chrome(service=ChromeService(executable_path=chrome_driver_path))
driver.get("https://www.baidu.com")
# 添加显示等待
# 创建显示等待类对象
wait = WebDriverWait(driver, 3)
wait.until(EC.invisibility_of_element_located((By.CSS_SELECTOR, "#\\31 > div > div > div > div > div > div.new-tag_4ozgi.new-text-link_3k9GD > div > div.flex-wrapper-top_3ucFS > div.flex-col-left_3trtY.baike-wrapper_6AORN.cu-pt-xs-lg.baike-wrapper-pc_26R04.cu-pt-xl.baike-wrapper-left-pc_5eYY8.cos-space-pb-sm > div > div > p > span:nth-child(1) > span")))
# 5、关闭浏览器
driver.quit()
显示等待可以等待隐式等待无法处理的问题。
无法等待弹窗,因为弹窗不是页面的元素,无法通过页面元素来定位到弹窗。
优点:显示等待是智能等待,可以自定义显示等待的条件,操作灵活
缺点:写法复杂
注:
隐式等待和显示等待不建议一起用,可能会导致不可预测的等待时间。
隐式等待设置为10s,显示等待设置为15s,那么结果会是15+10=25s吗?
import time
import datetime
from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from webdriver_manager.chrome import ChromeDriverManager
# 1.打开浏览器
chrome_driver_path = r"D:\Program Files\Python39\Scripts\chromedriver.exe"
# 1.打开浏览器
driver = webdriver.Chrome(service=ChromeService(executable_path=chrome_driver_path))
driver.get("https://www.baidu.com")
# 隐式等待设置为10s,显示等待设置为15s,那么结果会是15+10=25s吗?
driver.implicitly_wait(10)
wait = WebDriverWait(driver,15)
start = time.time()
try:
res = wait.until(EC.presence_of_element_located((By.XPATH, '//*[@id="2"]/div/div/div[3]/div[1]/div[1]/div/div/div')))
except:
end = time.time()
print("no such element")
driver.quit()
print(end-start)
打印:
"D:\Program Files\Python39\python.exe" D:/code/python/测试/_6test.py
no such element
21.065956354141235
进程已结束,退出代码0