有时定位不到元素,是因为页面打开了新窗口,因此我们要定位到新窗口里
mainWindow = dr.current_window_handle #保存主页面句柄
urlEle = driver.find_element_by_xpath("xpath").get_attribute("href") #定位链接元素
js = "window.open('"+urlEle+"');" #新窗口打开链接
# 如果打开的网页是固定地址 js = "window.open('https://www.baidu.com')"
dr.execute_script(js)
#循环页面句柄,获取非主页句柄,只适用于2个页面窗口的情况下
toHandle = dr.window_handles
方法一:
for handle in toHandle:
if handle == mainWindow:
continue
dr.switch_to_window(handle)
方法二,如果知道句柄在数据组的位置,可以直接使用下标:
dr.switch_to_window(toHandle[1])
方法三,使用title:
for handle in toHandle:
if handle.title = 'Title' :
break
dr.switch_to_window(handle)
print(dr.title) #打印的是新窗口的标题
有时selenium会报错, Element is not clickable at point,可能是因为页面窗口未全部显示,导致元素被隐藏
解决方法有2种:
dr.maximize_window() 页面最大化
js = "window.scrollTo(100,450)" 定位元素的X Y轴
dr.execute_script(js)
获取X Y轴的方法:
var box=document.getElementsByClassName('user-header-personal')[0] #注意就算只有一个元素 也要写上[0],js默认为数组
box.getBoundingClientRect().top
box.getBoundingClientRect().left
更多内容请访问:IT源点
注意:本文归作者所有,未经作者允许,不得转载