zoukankan      html  css  js  c++  java
  • python3+selenium3自动化测试—元素等待-等待显示

    在打开网页定位元素的时候,在网络不好或者页面卡顿的情况下会导致元素定位失败,此时不建议使用sleep()强制等待。

    首先正常导入模块

    1 from selenium import webdriver
    2 from selenium.webdriver.support.ui import WebDriverWait
    3 from selenium.webdriver.support import expected_conditions as EC
    4 from selenium.webdriver.common.by import By
    5 from time import sleep

    上面的模块分别为:

    WebDriverWait:显示等待模块(必用)
    expected_conditions:预期条件类(里面包含方法可以调用,用于等待显示)
    By:用于定位元素
    as的作用类似于定义一个变量,即把“
    expected_conditions”定义为“as”,后期代码书写便捷
    1 driver=webdriver.Firefox()
    2 
    3 driver.get("http://baidu.com")
    4 sleep(2)
    5 
    6 driver.find_element_by_css_selector("#kw").send_keys("Selenium")

    正常打开百度网页

     1 element=WebDriverWait(driver,5,0.5).until(EC.presence_of_element_located((By.ID,'su')))

    定义一个值,打开网页后等待五秒,每0.5秒请求一次,知道可以获取到ID='su'的这个元素

     1 element.click() 

    点击按钮

    全部代码如下

     1 from selenium import webdriver
     2 from selenium.webdriver.support.ui import WebDriverWait
     3 from selenium.webdriver.support import expected_conditions as EC
     4 from selenium.webdriver.common.by import By
     5 from time import sleep
     6 
     7 
     8 driver=webdriver.Firefox()
     9 
    10 driver.get("http://baidu.com")
    11 sleep(2)
    12 
    13 driver.find_element_by_css_selector("#kw").send_keys("Selenium")
    14 
    15 element=WebDriverWait(driver,5,0.5).until(EC.presence_of_element_located((By.ID,'su11')))
    16 
    17 element.click()
    18 
    19 sleep(3)
  • 相关阅读:
    了解一些常用的牛逼编译器(不限制编程语言, 不限制平台)
    Linux下的常用文本编辑器
    linux下一些重要命令的了解
    linux学习笔记(二:权限)
    liunx学习笔记(一:常用命令)
    文件操作相关的函数总结
    关于动态内存malloc和realloc
    实现一个简易的通讯录
    qsort函数排序各种类型的数据。
    结构体总结
  • 原文地址:https://www.cnblogs.com/HYL1003597280/p/14311124.html
Copyright © 2011-2022 走看看