美文网首页
selenium设置元素等待与until判断条件

selenium设置元素等待与until判断条件

作者: DD丿 | 来源:发表于2021-09-02 16:56 被阅读0次

    1. 设置元素等待

    前面我们接触了几个元素等待方法,sleep、implicitly_wait方法,这一章我们就来整体学一下。

    现在大多数Web应用程序使用的都是AJAX技术。当浏览器加载页面时,页面上的元素可能并不是同时被加载完成的,这给元素的定位增加了困难。如果因为在加载某个元素时延迟而造成ElementNotVisibleException的情况出现,那么就会降低自动化脚本的稳定性,我们可以通过设置元素等待,来改善这种问题造成的不稳定。

    WebDriver提供了两种类型的等待:显示等待和隐式等待。

    1.1 显示等待

    显式等待使WebDriver等待某个条件处理时继续执行,否则在达到最大时长时抛弃超时异常(TimeoutException)。

    1. from selenium import webdriver

    2. from selenium.webdriver.common.by import By

    3. from selenium.webdriver.support.ui import WebDriverWait

    4. from selenium.webdriver.support import expected_conditions as EC

    5. wd = webdriver.Chrome()

    6. wd.get('https://www.baidu.com/')

    7. a = WebDriverWait(wd,10).until(EC.presence_of_element_located((By.ID,"kw")))

    8. a.send_keys('selenium')

    WebDriverWait类是由WebDriver提供的等待方法。在设置时间内,默认每隔一段时间检测一次当前页面元素是否存在,如果超过设置时间检测不到则抛出异常。

    1. WebDriverWait(driver, timeout, poll_frequency=POLL_FREQUENCY, ignored_exceptions=None)

    driver:浏览器驱动

    timeout:最长超时时间,默认以秒为单位

    poll_frequency:检测的间隔(步长)时间,默认为0.5S

    ignored_exceptions:超时后的异常信息,默认情况下抛NoSuchElementException异常

    WebDriverWait()一般和until()或until_not()方法配合使用。

    <pre class="prettyprint linenums prettyprinted" style="box-sizing: border-box; margin: 20px 0px; padding: 0px; overflow: hidden; white-space: pre; overflow-wrap: break-word; background-color: rgb(68, 68, 68); border: 1px solid rgb(39, 40, 34); font: 14px / 20px "courier new"; color: rgb(102, 102, 102); border-radius: 3px; box-shadow: rgb(70, 71, 65) 40px 0px 0px inset, rgb(70, 71, 65) 41px 0px 0px inset;">

    1. until(method, message='')

    调用该方法提供的驱动程序作为一个参数,直到返回值为True。

    <pre class="prettyprint linenums prettyprinted" style="box-sizing: border-box; margin: 20px 0px; padding: 0px; overflow: hidden; white-space: pre; overflow-wrap: break-word; background-color: rgb(68, 68, 68); border: 1px solid rgb(39, 40, 34); font: 14px / 20px "courier new"; color: rgb(102, 102, 102); border-radius: 3px; box-shadow: rgb(70, 71, 65) 40px 0px 0px inset, rgb(70, 71, 65) 41px 0px 0px inset;">

    1. until_not(method, message='')

    调用该方法提供的驱动程序作为一个参数,直到返回值为False。

    在上面那个例子中,通过as关键字将expected_conditions重命名为EC,并调用presence_of_element_located()方法判断元素是否存在。

    expected_conditions类提供的预期条件判断的方法如下所示:

    title_is:判断当前页面的标题是否等于预期

    title_contains:判断当前页面的标题是否包含预期字符串

    presence_of_element_located:判断元素是否被加在DOM树里,并不代表元素一定可见

    visibility_of_element_located:判断元素是否可见(可见代表元素非隐藏,并且元素的宽和高都不等于0)

    visibility_of:与上一个方法作用相同,只是上一个方法参数为,该方法接收的参数为定位后的元素

    presence_of_all_elements_located:判断是否至少有一个元素存在于DOM树中。例如,在页面中有n个元素的class为“wp”,那么只要有一个存在就返回True

    text_to_be_present_in_element:判断某个元素中的text是否包含了预期的字符串

    text_to_be_present_in_element_value:判断某个元素的value属性是否包含了预期的字符串

    frame_to_be_available_and_switch_to_it:判断该表单是否可用切换进去,如果可用,返回True并且switch进去,否则返回False

    invisibility_of_element_located:判断某个元素是否不存在于DOM树或不可见

    element_to_be_clickable:判断元素是否可见并且是可以点击的

    staleness_of:等到一个元素从DOM树中移除

    element_to_be_selected:判断某个元素是否被选中,一般用在下拉列表

    element_selection_state_to_be:判断某个元素的选择状态是否符合预期

    element_located_selection_state_to_be:与上一个方法作用相同,只是上一个方法参数为单位后的元素,该方法接收的参数为定位

    alert_is_present:判断页面上是否存在alert

    除expected_conditions所提供的丰富的预期条件判断方法外,还可以使用is_displayed()方法来判断元素是否可见。

    <pre class="prettyprint linenums prettyprinted" style="box-sizing: border-box; margin: 20px 0px; padding: 0px; overflow: hidden; white-space: pre; overflow-wrap: break-word; background-color: rgb(68, 68, 68); border: 1px solid rgb(39, 40, 34); font: 14px / 20px "courier new"; color: rgb(102, 102, 102); border-radius: 3px; box-shadow: rgb(70, 71, 65) 40px 0px 0px inset, rgb(70, 71, 65) 41px 0px 0px inset;">

    1. from selenium import webdriver

    2. from time import sleep,ctime

    3. wd = webdriver.Chrome()

    4. wd.get('https://www.baidu.com/')

    5. print(ctime())

    6. for i in range(10):

    7. try:

    8. el = wd.find_element_by_id("kw22")

    9. if el.is_displayed():

    10. break

    11. except:pass

    12. sleep(1)

    13. else:

    14. print("time out")

    15. wd.close()

    16. print(ctime())

    </pre>

    相对来说,这种方式更容易理解,通过for循环10次,每次循环判断元素的is_displayed()状态是否为True。如果为True,则break跳出循环;否则sleep(1)后继续循环判断,直到10次循环结束后,打印“time out”信息。

    执行结果如下:

    image

    1.2 隐式等待

    隐式等待是通过一定的时长等待页面上某元素加载完成。如果超出了设置的时长元素还没有被加载,则抛出NoSuchElementException异常。WebDriver提功力implicitly_wait()方法来实现隐式等待,默认设置为0。它的用法相对来说要简单得多。

    1. from selenium import webdriver

    2. from selenium.common.exceptions import NoSuchElementException

    3. from time import ctime

    4. wd = webdriver.Chrome()

    5. 设置隐式等待为10秒

    6. wd.implicitly_wait(10)

    7. wd.get('https://www.baidu.com/')

    8. try:

    9. print(ctime())

    10. wd.find_element_by_id("kw22").send_keys('selenium')

    11. except NoSuchElementException as e:

    12. print(e)

    13. finally:

    14. print(ctime())

    </pre>

    Implicitly_wait()默认参数的单位为秒,本例中设置等待时长为10秒。首先这10秒并非一个固定的等待时间。它并不影响脚本的执行速度。其次,它并不针对页面上的某一个元素进行等待。当脚本执行到某个元素定位时,如果元素可以定位,则继续执行;如果元素定位不到,则它将以循环查询的方式不断地判断元素是否被定位到。假设在第3秒定位到了元素,则继续执行,若知道超出设置时长(10秒)还没有定位到元素,则抛出异常。

    在上面的例子中,显然百度输入框的定位id=kw22是有误的,通过打印的两次时间可以看出,当执行对百度输入框的操作时,超过了10秒的等待。

    image

    1.3 sleep休眠方法

    在前面我们就使用过sleep方法了,只不过没有详细的介绍,现在就把这个归入到这个大标题中来介绍下。

    有时候我们希望脚本在执行到某一个位置时做固定时间的休眠,尤其是在脚本调试中。这时可以使用sleep()方法,需要说明的是,sleep()方法由python的time模块提供。

    1. from selenium import webdriver

    2. from time import sleep

    3. wd = webdriver.Chrome()

    4. wd.get('https://www.baidu.com/')

    5. sleep(2)

    6. wd.find_element_by_id("kw").send_keys("selenium")

    7. wd.find_element_by_id("su").click()

    8. sleep(5)

    9. wd.quit()

    </pre>

    当执行到sleep()方法时会固定休眠一定的时长,然后再继续执行。sleep()方法默认参数以秒为单位,如果设置时长小于1秒,则可以用小数表示,如果sleep(0.5)表示休眠0.5秒。

    回到顶部(go to top)

    2. 上传文件

    上传文件是比较常见的Web功能之一,但WebDriver并没有提供专门用于上传的方法,如何实现上传操作关键在于上传文件的思路。

    一般Web页面的上传功能的操作需要点击“上传”按钮后打开本地的Window窗口,从窗口中选择本地文件进行上传。而WebDriver是无法操作Windows控件的,所以,对于初学者来说,一般思路会卡在如何识别Window控件这个问题上。

    对于Web页面的上传功能实现一般有一下两种方式。

    普通上传:普通的附件上传是将本地文件的路径作为一个值放在input标签中,通过form表单将这个值提交给服务器。

    插件上传:一般是指基于Flash、JavaScript或Ajax等技术所实现的上传功能。

    插件上传不适合放在自动化里面讲解,可能会放在python高级编程里面讲解。对于通过input标签实现的上传功能,可以将其看作是一个输入框,通过send_keys()指定本地文件路径的方式实现文件上传。

    html代码:

    1. <!DOCTYPE html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <title></title>
    6. </head>
    7. <body>
    8. <div class="row-fluid">
    9. file:<input type="file" name="file" />
    10. </div>
    11. </body>
    12. </html>

    通过浏览器打开,效果如下图所示:

    image

    <pre class="prettyprint linenums prettyprinted" style="box-sizing: border-box; margin: 20px 0px; padding: 0px; overflow: hidden; white-space: pre; overflow-wrap: break-word; background-color: rgb(68, 68, 68); border: 1px solid rgb(39, 40, 34); font: 14px / 20px "courier new"; color: rgb(102, 102, 102); border-radius: 3px; box-shadow: rgb(70, 71, 65) 40px 0px 0px inset, rgb(70, 71, 65) 41px 0px 0px inset;">

    1. from selenium import webdriver

    2. wd = webdriver.Chrome()

    3. wd.get('http://127.0.0.1:8020/day01/index.html')

    4. 定位上传按钮,添加本地文件

    5. wd.find_element_by_name("file").send_keys('E:\1.png')

    通过这种方法上传,就避免了操作Windows控件的步骤。如果能找到上传的input标签,那么基本上就可以通过send_keys()方法向其输入一个文件地址来实现上传。

    回到顶部(go to top)

    3. 下载文件

    WebDriver允许我们设置默认的文件下载路径,也就是说,文件会自动下载并且存放到设置的目录中。下面以谷歌浏览器为例,执行文件的下载。

    1. from selenium import webdriver

    2. import os

    3. options = webdriver.ChromeOptions()

    4. prefs = {'profile.default_content_settings.popups':0,'download.default_directory':'E:\'}

    5. options.add_experimental_option('prefs',prefs)

    6. wd = webdriver.Chrome(executable_path=r'E:\webdrivers\chromedriver.exe',chrome_options=options)

    7. wd.get('')#输入要下载的文件所在网页

    8. wd.find_element_by_xpath('').click()#点击文件所在位置的元素

    </pre>

    download.default_directory:指定路径
    profile.default_content_settings.popups:0 为屏蔽弹窗,1 为开启弹窗

    不同的浏览器设置方法也不同,以上例子值针对谷歌浏览器。火狐浏览器的下载设置就是其他类型的方法了。

    例子:# 显示等待10秒,直到页面右边的"相关术语"出现
    WebDriverWait(px, 10).until(EC.presence_of_element_located((By.CLASS_NAME,
    "opr-recommends-merge-p"))) # 获取页面右边的"相关术语"element2 = driver.find_element_by_class_name("opr-recommends-merge-p")print(element2)


    作者:@小灰灰
    本文为作者原创,转载请注明出处:https://www.cnblogs.com/liuhui0308/p/11960883.html

    相关文章

      网友评论

          本文标题:selenium设置元素等待与until判断条件

          本文链接:https://www.haomeiwen.com/subject/cjlcwltx.html