1. 程式人生 > >Python+Selenium 定位頁面元素

Python+Selenium 定位頁面元素

bdr web ren https con 框架 content 進行 www.

1.跳轉到Frame/Iframe ,再定位元素
理解:frame的實質,frame中實際上是嵌入了另一個頁面,而webdriver每次只能在一個頁面識別,因此需要先定位到相應的frame,對那個頁面裏的元素進行定位

1.1方法一
如果iframe有name或id的話,直接使用switch_to_frame("name值")或switch_to_frame("id值")。如下:
driver=webdriver.Firefox()
driver.get(r‘http://www.126.com/‘)
driver.switch_to_frame(‘x-URS-iframe‘) #需先跳轉到iframe框架

username=driver.find_element_by_name(‘email‘)
username.clear()

1.1方法二
如果iframe沒有name或id的話,則可以通過下面的方式定位:
#先定位到iframe
elementi= driver.find_element_by_class_name(‘APP-editor-iframe‘)
#再將定位對象傳給switch_to_frame()方法
driver.switch_to_frame(elementi)

PS:完成操作後,可以通過switch_to.parent_content()方法跳出當前iframe,或者還可以通過switch_to.default_content()方法跳回最外層的頁面

2.Xpath 層級定位
2.1 通過絕對路徑定位
例如:find_element_by_xpath("/html/body/div/div/div[2]/div[3]/a[2]").click()

絕對路徑是從當前元素往前數最近的一個html 開始數的。
2.2 利用元素屬性定位
地圖有三個屬性,href,name,class。

driver.findElement(By.xpath("//a[@name=‘tj_trnews‘]")).click();

    driver.findElement(By.xpath("//a[@href=‘http://news.baidu.com‘]")).click()

driver.findElement(By.xpath("//a[@class=‘mnav‘]")).click();

    driver.findElement(By.xpath("//a[contains(@href,\"http://map.baidu.co\")]")).click();

參考資料:
https://www.cnblogs.com/csj2018/p/9194618.html 
https://www.cnblogs.com/yufeihlf/p/5689042.html
http://www.cnblogs.com/yufeihlf/p/5717291.html 

Python+Selenium 定位頁面元素