selenium之元素定位方法


  在元素定位时候,有个同事来问我有个新建按钮死活定位不到,说到定位不到,一般存在以下几种情况(仅我遇到的做个总结):

  1. 元素定位方法不对,换一种方法
  2. 存在ifame
  3. 页面加时间比较长
  4. 需要切换窗口才可以
  5. 元素不唯一

        好,这时候我同事来说试了前面4种情况都不对,这时候我想到的是第5种方法,下面我将介绍下一般元素定位不到的几种情况的处理方法

       1.元素不唯一定位方法如下

  将元素定位复制到F12搜索框中,类似百度如下图,假如我们要定位设置按钮,但是通过name方法我们搜索发现,元素不是唯一的,这时候我们需要用到循环遍历的方法。

        

        定位一组元素与定位一个元素的方法一致,只是方法名中的find_element变为find_elements。定位一组元素会返回一个元素列表,具体操作时需要取其中的一个元素进行操作。

# coding=utf-8
from selenium import webdriver


base_url = "http://www.baidu.com"
driver = webdriver.Chrome()
driver.get(base_url)
driver.maximize_window()
# 用找到所有元素的方法找出不唯一的所有元素
s = driver.find_elements_by_name("tj_settingicon")
#打印看下一共有多少个
print(len(s))
#循环遍历一下取到你想要的元素是哪一个
for i in range(len(s)):
    print "第"+str(i)+"个元素"
    print s[i].get_attribute("name")

#如果是第一个元素则如以下方法写即可
driver.find_elements_by_name("tj_settingicon")[0].click()

  2.切换窗口方法

        

  在页面操作过程中有时候点击某个链接会弹出新的窗口,这时就需要主机切换到新打开的窗口上进行操作。Webdriver提供了switch_to.window()方法,可以实现在不同的窗口之间切换。
       

current_window_handle:获得当前窗口句柄。
window_handles:返回所有窗口的句柄到当前会话。
switch_to.window():用于切换到相应的窗口。
  # 重新定义切换页面标签方法,切换到最新的窗口
    def swith_to_current_window(self):
        handles = self.driver.window_handles  # 获取当前窗口句柄集合(列表类型)
        # print handles  # 输出句柄集合
        # count = len(handles)
        # end_index=count-1
        handle = handles[-1]   #最新打卡的窗口句柄
        if handle != self.driver.current_window_handle:
            # print 'switch to ', handle
            self.driver.switch_to_window(handle)
            print self.driver.title
        return handles, handle
# 重新定义切换页面标签方法,选择第一个窗口
    def swith_to_window(self):
        handles = self.driver.window_handles  # 获取当前窗口句柄集合(列表类型)
        # print handles  # 输出句柄集合
        # count = len(handles)
        # end_index=count-1
        handle = handles[0]  # 最新打卡的窗口句柄
        if handle != self.driver.current_window_handle:
            # print 'switch to ', handle
            self.driver.switch_to_window(handle)
            print self.driver.title
        return handles, handle

  3.切换iframe

  在web应用中经常会遇到frame/iframe表单嵌套页面的应用,webdriver只能在一个页面上对元素识别和定位,对于frame/iframe表单内嵌页面上的元素无法直接定位。这时就需要通过switch_to_frame方法将当前定位的主体切换到内嵌页面中。

        切一层iframe:

switch_to.frame(“Editor_Edit_EditorBody_ifr”)

  从iframe中切出:

switch_to_default_content()

  切到父级iframe:

#跳出当前一级表单,对应离他最近的switch_to.frame。
switch_to.parent_frame()

  4.验证css定位方法写的是否正确

       比如我们要定位百度一下这个元素:

     

  我们通过id来定位,用css方法来定位:

       第一步:右键copy  #su:

        第二步:切换到console窗口,输入document.querySelector("#su"),可以看到可以定位到此元素,且是唯一的