有時定位不到元素,是因為頁面打開了新窗口,因此我們要定位到新窗口里
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

