首页 > 其他分享 >一、使用Expected_conditions判断元素是否可见-6

一、使用Expected_conditions判断元素是否可见-6

时间:2022-08-17 10:23:21浏览次数:64  
标签:webdriver driver 元素 selenium EC element Expected import conditions

1、处理定位报错的问题

  • 判断该元素存在,再输入。
  • 判断该元素不存在,抛出异常。
  • 依然是通过EC这个模块。

2、判断是否存在邮箱地址,存在,再操作。

  • 就不用担心元素不存在,程序报错。

3、判断传入的元素是否可见,是否在显示范围内。

  • 还是要先找元素
  • 但这样找,只能顺利的执行一次。
from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC

element = driver.find_element_by_class_name("controls")
EC.visibility_of_element_located(element)

4、再加,在多少时间内,找相应元素,找到则返回true。否则为false。

  • 这里传的是定位方式和定位值,只用通过by方式就可以了。并非WebElement。
  • 同时,要添加close,因为每次实例化一个driver,可以看任务管理器,没有关闭。会导致加载很慢。
#coding=utf-8
from selenium import webdriver
import time
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
driver.get("http://www.5itest.cn/register")
time.sleep(5)
print(EC.title_contains("注册"))

localor = (By.CLASS_NAME,"controls")
WebDriverWait(driver,10).until(EC.visibility_of_element_located(localor))
driver.close()
PS D:\imooc\selenium> python .\start_browser.py

DevTools listening on ws://127.0.0.1:50745/devtools/browser/110e1640-0de6-447b-b243-a87c74a05029
<selenium.webdriver.support.expected_conditions.title_contains object at 0x000001F4B97616A0>
  •  当找不到时:
PS D:\imooc\selenium> python .\start_browser.py

DevTools listening on ws://127.0.0.1:51306/devtools/browser/342f159f-d7a9-485f-aade-27ce58b5b342
<selenium.webdriver.support.expected_conditions.title_contains object at 0x0000021D78F516A0>
Traceback (most recent call last):
  File ".\start_browser.py", line 16, in <module>
    WebDriverWait(driver,10).until(EC.visibility_of_element_located(localor))
  File "D:\Python\lib\site-packages\selenium\webdriver\support\wait.py", line 80, in until
    raise TimeoutException(message, screen, stacktrace)
selenium.common.exceptions.TimeoutException: Message:

 

标签:webdriver,driver,元素,selenium,EC,element,Expected,import,conditions
From: https://www.cnblogs.com/jieqiong1755/p/16593867.html

相关文章