Selenium webdriver 元素定位方法總結

我是6毛發表於2016-07-01

<input id="kw" class="s_ipt" autocomplete="off" maxlength="255" value="" name="wd"/>

<a class="mnav" name="test" href="http://news.baidu.com">新聞板塊</a>

上面是百度輸入框的程式碼


from selenium import webdriver


1. find_element_by_id("kw")

2. find_element_by_name("wd")

3. find_element_by_class_name("s_ipt")

4. find_element_by_tag_name("input")

5. find_element_by_link_text("新聞板塊")

6. find_element_by_partial_link_text("新")


7.1 XPath-絕對路徑定位:

絕對路徑類似於你家的地址:XX市XX區XX路XX號;也就是說從最外層的標籤開始往裡數就可以了

例如百度輸入框的絕對路徑:

find_element_by_xpath("html/body/div[3]/div/div/div/div/form/span/input")

div[3] 代表當前層級第3個div


7.2 XPath-利用元素屬性定位

find_element_by_xpath("//input[@id='kw']")

find_element_by_xpath("//input[@name='wd']")

find_element_by_xpath("//*[@id='kw']")

//input表示查詢頁面上所有的input元素

//*表示查詢頁面上所有元素

//input[1]表示查詢頁面上第一個input元素

//form[1]/input 表示查詢第一個form元素下一級的input元素

//form[1]//input 表示查詢頁面上第一個form元素下的所有input元素,不管巢狀了多少層

//input[@id='kw' and @class='su'] 可以用 and 連線多個屬性來唯一標識一個元素


Firepath可以生成XPath


8.css定位

find_element_by_css_selector("#kw")  #符號表示通過ID屬性來定位元素

find_element_by_css_selector(".s_ipt")   點符號(.)表示通過class屬性來定位元素

find_element_by_css_selector("input")    通過Tag標籤來定位元素時不需要任何符號

find_element_by_css_selector("[id=kw]")  通過屬性和屬性值來定位元素,可以使用任意屬性,例如 [type=submit]

find_element_by_css_selector(“span>input”)  通過父子關係定位元素

find_element_by_css_selector(“span+input”) 表示查詢同一級緊挨著span的input元素

以上幾種方式還可以綜合使用

  



 


我個人喜歡用By定位元素

要使用By需要先import


from selenium.webdriver.common.by import By

1. find_element(By.ID,"kw")

2. find_element(By.NAME,"wd")

3. find_element(By.CLASS_NAME,"s_ipt")

4. find_element(By.TAG_NAME,"input")

5. find_element(By.LINK_TEXT,"新聞板塊“)

6. find_element(By.PARTIAL_LINK_TEXT,"新”)

7. find_element(By.XPATH,"//*[@class='s_ipt']")

8. find_element(By.CSS_SELECTOR,“#kw”)


相關文章