selenium 定位元素不稳定怎么解决?

脚本问答题导致测试用例不稳定,DOM还没加载出元素就执行了脚本导致报回错,这种只要使用答显式等待大部分都能解决。

 ###############

from selenium import webdriver

from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import  expected_conditions as EC
from time import sleep


# 实例化浏览器
driver = webdriver.Firefox()
driver.get("https://www.baidu.com")
element = (By.CSS_SELECTOR,'#kw')
WebDriverWait(driver,10).until(EC.presence_of_element_located(element)).send_keys('admin')
sleep(2)
driver.quit()

可以分开写:
driver = webdriver.Firefox()
driver.get("https://www.baidu.com")
element = (By.CSS_SELECTOR,'#kw')
wait = WebDriverWait(driver,10)
element = wait.until(EC.presence_of_element_located(element))
element.send_keys('admin')
sleep(2)
driver.quit()

如果找不到元素,会报出一个异常,

################

 

posted @ 2020-05-19 17:29  技术改变命运Andy  阅读(983)  评论(0编辑  收藏  举报