selenium元素等待及滚动条滚动

selenium三大等待,sleep(强制)、implicitlyWait(隐式等待)、WebDriverWait(显式等待),主要记一下最后面的WebDriverWait。

WebDriverWait是三大等待中最常用也是最好用的一种等待方式,比起另外两种而言,B格更高、更智能。写法为:

 
  
  1. #WebDriverWait(driver,等待总时长,查询间隔时间).until(EC.visibility_of_element_located((By.XPATH,Xpath公式)))

  2. # 例如:

  3. cj = '//span[text()="19/05/27"]/parent::p/parent::div/preceding-sibling::div[@class="announce-cont clearfix"]//a[text()="查看成绩"]'

  4. WebDriverWait(driver,30,0.5).until(EC.visibility_of_element_located((By.XPATH,cj)))

 在iframe中也可以使用WebDriverwait,例如:

 
  
  1. WebDriverWait(driver,30,0.5).until(EC.frame_to_be_available_and_switch_to_it("login_frame_qq"))

  2. # 其中"login_frame_qq"是iframe的name属性;

  3. # "EC.frame_to_be_available_and_switch_to_it"这句话的意思是等待并切换至,也就是说这句话等同"EC.visibility_of_element_located"+"driver.switch_to_frame"

例子中的等待含义为总时长30S,每间隔0.5S查询一次until括号中的函数。EC为selenium.webdriver.support.expected_conditions的缩写,visibility_of_element_located的用法是查询后跟元祖中指定的元素是否可见。

要格外注意的是visibility_of_element_located()中只能传入一个函数,所以一般使用(By.XPATH,xpath)源码:

 
  
  1. class visibility_of_element_located(object):

  2. """ An expectation for checking that an element is present on the DOM of a

  3. page and visible. Visibility means that the element is not only displayed

  4. but also has a height and width that is greater than 0.

  5. locator - used to find the element

  6. returns the WebElement once it is located and visible

  7. """

  8. def __init__(self, locator):

  9. self.locator = locator

  10. def __call__(self, driver):

  11. try:

  12. return _element_if_visible(_find_element(driver, self.locator))

  13. except StaleElementReferenceException:

  14. return False

再来看一下滚轮滑动的几种用法

  1.滑动到指定元素顶端显示:

 
  
  1. driver.execute_script('argument[0].scrollIntoView();',driver.find_element_by_xpath(xpath)) 

 2.滑动到指定元素底端显示:

driver.execute_script('argument[0].scrollIntoView(false);',driver.find_element_by_xpath(xpath))

3.页面滑动到底端:

driver.execute_script('windows.scrollto(0,document.body.scrollHeight)')

4.页面滑动到顶端:

driver.execute_script('windows.scrollto(document.body.scrollHeight)')

其中包含指定元素的使用时只用注意scrollIntoView后是否跟随false,有则底端、无则顶端;其次页面滑动时只用注意最后是否从0开始,从0开始则为底端、无则顶端

  顺带说一下driver.execute_script()这个函数,这个函数括号内主要跟随js语句

  用法例如:

 
  
  1. driver.execute_script('argument[0].scrollIntoView(false);'

  2. 'var a = argument[1]',driver.find_element_by_xpath(xpath),num1)

  3. # 其带入的参数没有数量限制,只是语法必须使用js语法

 

感谢每一个认真阅读我文章的人,礼尚往来总是要有的,虽然不是什么很值钱的东西,如果你用得到的话可以直接拿走:

selenium元素等待及滚动条滚动_第1张图片

这些资料,对于【软件测试】的朋友来说应该是最全面最完整的备战仓库,这个仓库也陪伴上万个测试工程师们走过最艰难的路程,希望也能帮助到你!有需要的小伙伴可以点击下方小卡片领取   

selenium元素等待及滚动条滚动_第2张图片

你可能感兴趣的:(selenium,python,测试工具,单元测试,测试用例,压力测试,功能测试)