元素定位分为单个元素定位和多个元素定位
一、单个元素(element)定位
以百度首页为例(https://www.baidu.com/)
1.通过id,name定位
1 # 导入webdriver包 2 from selenium import webdriver 3 from time import sleep 4 5 driver = webdriver.Firefox() #创建火狐对象 6 driver.get("https://www.baidu.com/") #打开baidu 7 driver.find_element_by_name("wd").send_keys("selenium") #通过name定位 8 driver.find_element_by_id("su").click() #通过id定位 9 sleep(5) #睡眠5毫秒 10 driver.quit() #关闭浏览器
2.通过Xpath定位
1 driver.find_element_by_xpath("//input[@id='kw']").send_keys("selenium") 2 driver.find_element_by_xpath("//input[@id='su']").click()
3.通过css完整路径定位(路径复制同上)
1 driver.find_element_by_css_selector("html body.zhs.zh-CN table#hp_table tbody tr td#hp_cellCenter.hp_hd div#hp_container div#sbox.sw_sform div.search_controls form#sb_form.sw_box div.b_searchboxForm input#sb_form_q.b_searchbox").send_keys("selenium")#通过css完整路径定位 2 driver.find_element_by_css_selector("html body.zhs.zh-CN table#hp_table tbody tr td#hp_cellCenter.hp_hd div#hp_container div#sbox.sw_sform div.search_controls form#sb_form.sw_box div.b_searchboxForm input#sb_form_go.b_searchboxSubmit").click()
4.通过CSS选择器定位
1 driver.find_element_by_css_selector(".s_ipt").send_keys("selenium")#通过css class定位 2 driver.find_element_by_css_selector("#su").click()#通过css id定位
二、多个元素(elements)定位
基于以下html
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 2 <html xmlns="http://www.w3.org/1999/xhtml"> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 5 <title>复选框实例</title> 6 </head> 7 <body> 8 请选择你喜欢的明星</br> 9 <input type= "checkbox" name = "idol" value = "FBB">范冰冰</br> 10 <input type= "checkbox" name = "idol" value = "YM">杨幂</br> 11 <input type= "checkbox" name = "idol" value = "YY">杨颖</br> 12 <input type= "checkbox" name = "idol" value = "GYY">高圆圆</br> 13 </body> 14 </html>
1.通过elements_tag_name定位一组元素
1 #!/usr/bin/env python 2 # _*_ coding:utf-8 _*_ 3 # 导入webdriver包 4 from selenium import webdriver 5 from time import sleep 6 driver = webdriver.Firefox() #创建火狐对象 7 driver.get("file:///C:/Users/Administrator/Desktop/idol.html") 8 inputs = driver.find_elements_by_tag_name("input") 9 for i in inputs: 10 if i.get_attribute("type") == "checkbox": 11 i.click() 12 sleep(1) 13 sleep(2) 14 driver.quit() #关闭浏览器
2.通过elements_by_Xpath定位一组元素
1 #!/usr/bin/env python 2 # _*_ coding:utf-8 _*_ 3 # 导入webdriver包 4 from selenium import webdriver 5 from time import sleep 6 driver = webdriver.Firefox() #创建火狐对象 7 driver.get("file:///C:/Users/Administrator/Desktop/idol.html") 8 checkboxs = driver.find_elements_by_xpath('//*[@name="idol"]') 9 for checkbox in checkboxs: 10 checkbox.click() 11 sleep(1) 12 sleep(2) 13 driver.quit() #关闭浏览器