一、frame架構裡面的元素定位
1.1 iframe定位 -- 先切換到iframe架構-定位-釋放iframe
定位到iframe 3種的方法
"""
Switches focus to the specified frame, by index, name, or webelement.
:Args:
- frame_reference: The name of the window to switch to, an integer representing the index,
or a webelement that is an (i)frame to switch to.
:Usage:
driver.switch_to.frame('frame_name') #通過名字
driver.switch_to.frame(1) #通過下标
driver.switch_to.frame(driver.find_elements_by_tag_name("iframe")[0]) #通過WebElement對象來定位
"""
1 #切換到iframe
2 driver.switch_to.frame("login_frame_qq")
3
4 #點選賬号密碼登入
5 driver.find_element_by_xpath('//a[@id="switcher_plogin"]').click()
6 time.sleep(2)
7 #輸入賬号密碼
8
9 #釋放iframe 回到首頁面
10 driver.switch_to.default_content()
二、頁面滾動條之後的元素定位及視窗切換
2.1 元素拖動到可見區域-定位
四個常見方法:
1)移動到元素element對象的“底端”與目前視窗的“底部”對齊:
driver.execute_script("arguments[0].scrollIntoView(false);",element)
2)移動到元素element對象的“頂端”與目前視窗的“頂部”對齊 :
driver.execute_script("arguments[0].scrollIntoView();",element)
3)移動到頁面底部:
driver.execute_script("window.scrollTo(0,document.body.scrollHeight)")
4)移動到頁面頂部:
driver.execute_script("window.scrollTo(document.body.scrollHeight,
0)")
如:
1 from selenium import webdriver
2 import time
3 from selenium.webdriver.support.wait import WebDriverWait
4 from selenium.webdriver.support import expected_conditions as EC
5 from selenium.webdriver.common.by import By
6
7 driver = webdriver.Chrome()
8 driver.get("https://www.baidu.com/")
9 driver.maximize_window()
10 time.sleep(3)
11
12 #定位百度搜尋框
13 driver.find_element_by_id("kw").send_keys("python")
14 time.sleep(3)
15 driver.find_element_by_id("su").click()
16 time.sleep(5)
17 #找到這個元素
18 ele = driver.find_element_by_xpath('//a[text()="_百度百科"]')
19 #拖動元素到可見區域--scrollIntoView() 拉到頂部顯示,有可能會被導航欄遮擋,定位不到而報錯;scrollIntoView(false)可視區域底部對齊
20 driver.execute_script("arguments[0].scrollIntoView(false);",ele)
21 time.sleep(5)
2.2 視窗切換
1)windows = driver.window_handles #擷取目前所有的視窗
2)driver.switch_to.window(windows[-1]) #切換到最新打開的一個視窗
3)driver.switch_to.window(windows[0]) #切換到第一個視窗
4)driver.current_window_handle() #擷取目前視窗句柄
1 #視窗切換
2 #擷取目前所有句柄 --傳回的是個清單
3 windows = driver.window_handles
4 ele.click()
5 time.sleep(10)
6
7 #等待新視窗打開
8 WebDriverWait(driver,10,0.5).until(EC.new_window_is_opened(windows))
9 #擷取目前所有句柄
10 windows = driver.window_handles
11 #切換到最後一個句柄 -- 根據傳回的清單下标取值
12 driver.switch_to.window(windows[-1])
13 #滑動到頁面最底部
14 driver.execute_script("window.scrollTo(0,document.body.scrollHeight)")
15 driver.current_window_handle()
16
17 time.sleep(5)
18 driver.quit()
轉載于:https://www.cnblogs.com/simran/p/9235853.html