selenium 元素定位方法
id | 唯一的 |
---|---|
name | 元素的名称 |
class name | 元素的类名 |
tag name | 标签,不推荐,重复率太高 |
link text | 文本链接 |
partial link text | 对文本链接的一种补充 |
xpath | 相对/绝对路径 |
css selector | css定位 |
-
通过id定位
driver.find_element_by_id(“kw”)
-
通过name定位
driver.find_element_by_name(“wd”)
-
通过class name定位
driver.find_element_by_class_name(“s_ipt”)
-
通过tag name定位
driver.find_element_by_tag_name(“input”)
这种定位元素方式特不靠谱,由于好多种原因定位元素失败,强烈不推荐这种方式
-
通过link text定位
<a href="http://tieba.baidu.com" target="_blank" class="mnav c-font-normal c-color-t">贴吧</a>
driver.find_element_by_link_text(“贴吧”)
-
通过partial link text定位
如果选取的文字链接比较长,可选取可作为唯一标识的部分文字
<a href="https://www.hao123.com" target="_blank" class="mnav c-font-normal c-color-t">hao123</a>
driver.find_element_by_partial_link_text(“hao”)
-
通过xpath定位
<html> <head> <body link="#0000cc"> <a id="result_logo" href="/" οnmοusedοwn="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">
driver.find_element_by_xpath("//*[@id=‘kw’]")
driver.find_element_by_xpath("//*[@name=‘wd’]")
driver.find_element_by_xpath("//input[@class=‘s_ipt’]")
driver.find_element_by_xpath("/html/body/form/span/input")
driver.find_element_by_xpath("//span[@class=‘soutu-btn’]/input")
driver.find_element_by_xpath("//form[@id=‘form’]/span/input")
driver.find_element_by_xpath("//input[@id=‘kw’ and @name=‘wd’]")
-
通过css定位,css的定位方法很多,也比较麻烦
以百度输入框为例
a. 通过id/class定位(css通过id属性定位,用#号表示id属性,css通过class属性定位,用.表示class属性)
driver.find_element_by_css_selector("#kw").send_keys(“css通过id属性定位”)
driver.find_element_by_css_selector(".s_ipt").clear()
b. 通过标签属性定位,无任何标识符,一般会加上一个固定属性,要不会容易出错定位失败
driver.find_element_by_css_selector(“input[class=s_ipt]”).send_keys(“css通过标签属性定位”)
driver.find_element_by_css_selector(“input#kw”).send_keys(“css通过标签属性定位”)
c. 通过其他html中的其他属性定位
driver.find_element_by_css_selector("[name=‘wd’]").send_keys(“css通过name属性定位”)
driver.find_element_by_css_selector("[autocomplete=‘off’]").clear()
其他方法比较复杂,比如css索引定位,层级关系定位等
实际工作中应该用最简单有效的定位方法去完成。