selenium之元素定位方法(持续更新)

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

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

        好,这时候我同事来说试了前面4种情况都不对,这时候我的办法是:

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

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

        

        

# 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.切换窗口方法

        

  # 重新定义切换页面标签方法,切换到最新的窗口
    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

  

猜你喜欢

转载自www.cnblogs.com/kaixinpianzi/p/10728605.html