几点 Selenium 使用细节

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/dszgf5717/article/details/82017779

1、implicitly_wait 隐式等待

# -*- coding:utf-8 -*-

"""
implicitly_wait():隐式等待
当使用了隐士等待执行测试的时候,如果 WebDriver没有在 DOM中找到元素,将继续等待,超出设定时间后则抛出找不到元素的异常
换句话说,当查找元素或元素并没有立即出现的时候,隐式等待将等待一段时间再查找 DOM,默认的时间是0
一旦设置了隐式等待,则它存在整个 WebDriver 对象实例的声明周期中,隐式的等到会让一个正常响应的应用的测试变慢,
它将会在寻找每个元素的时候都进行等待,这样会增加整个测试执行的时间。
"""

from selenium import webdriver 
import time

driver = webdriver.Firefox()
driver.get('http://demo.tutorialzine.com/2009/09/simple-ajax-website-jquery/demo.html')

#等待10秒
driver.implicitly_wait(10)
driver.find_element_by_link_text("Page 4").click()

message = driver.find_element_by_id('pageContent')
#等待 Ajax 的内容出现
time.sleep(4)
print "Nunc nibh tortor" in message.text

2、设置加载超时

try:
    driver.set_page_load_timeout(30)
    driver.set_script_timeout(30)
    driver.get(url)
except:
    traceback.print_exc()
finally:
    driver.close()
    driver.quit()

3、获取元素信息

x = driver.execute_script('return document.getElementsByClassName("class")[0].x')
# 获取多个链接
for link in driver.find_elements_by_xpath("//*[@href]"):
    print(link.get_attribute('href'))
# 获取单个链接
driver.find_element_by_xpath("//*[@href]").get_attribute('href')

猜你喜欢

转载自blog.csdn.net/dszgf5717/article/details/82017779