多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
[TOC] ## 概述 Selenium提供了8种定位方式。 ``` id -> find_element_by_id() name -> find_element_by_name() class name -> find_element_by_class_name() tag name -> find_element_by_tag_name() link text -> find_element_by_link_text() partial link text -> find_element_by_partial_link_text() xpath -> find_element_by_xpath() css selector -> find_element_by_css_selector() //定位一组元素 find_elements_by_id() find_elements_by_name() find_elements_by_class_name() find_elements_by_tag_name() find_elements_by_link_text() find_elements_by_partial_link_text() find_elements_by_xpath() find_elements_by_css_selector() ``` ## 定位用法 ``` <html> <head> <body link="#0000cc"> <a id="result_logo" href="/" onmousedown="return c({'fm':'tab','tab':'logo'})"> <form id="form" class="fm" name="f" action="/s"> <span class="soutu-btn"></span> <input id="kw" class="s_ipt" name="wd" value="" maxlength="255" autocomplete="off"> ``` ### 通过tag name定位: `dr.find_element_by_tag_name("input") ` 通过css定位,css定位有N种写法,这里列几个常用写法: ``` dr.find_element_by_css_selector("#kw") dr.find_element_by_css_selector("[name=wd]") dr.find_element_by_css_selector(".s_ipt") dr.find_element_by_css_selector("html > body > form > span > input") dr.find_element_by_css_selector("span.soutu-btn> input#kw") dr.find_element_by_css_selector("form#form > span > input") ``` ### 文本链接。 <a class="mnav" href="http://news.baidu.com" name="tj_trnews">新闻</a> <a class="mnav" href="http://www.hao123.com" name="tj_trhao123">hao123</a> 通过link text定位: ``` dr.find_element_by_link_text("新闻") dr.find_element_by_link_text("hao123") ``` 通过link text定位: ``` dr.find_element_by_partial_link_text("新") dr.find_element_by_partial_link_text("hao") dr.find_element_by_partial_link_text("123") ``` ## 定位一组元素 ``` texts = driver.find_element_by_css_selector('a') # 循环遍历出每一条搜索结果的标题 for t in texts: print(t.text) ```