selenium之CSS定位汇总

以百度首页为例:

定位输入框

一:单一属性定位

1:type selector

driver.find_element_by_css_selector('input')

2:id 定位

driver.find_element_by_css_selector('#kw')

3:class 定位

driver.find_element_by_css_selector('.s_ipt')

4:其他属性定位

driver.find_element_by_css_selector('[name='wd']')

driver.find_element_by_css_selector("[type='text']")

二:组合属性定位

1:id 组合属性定位

driver.find_element_by_css_selector("input#kw")

2:class 组合属性定位

driver.find_element_by_css_selector("input.s_ipt")

3:其他属性组合定位

driver.find_element_by_css_selector("input[name='wd']")

4:仅有属性名,没有值也可以

driver.find_element_by_css_selector("input[name]")

5:两个其他属性组合定位

driver.find_element_by_css_selector("[name='wd'][autocomplete='off']")

6:模糊匹配属性值方法

以百度首页点击按钮为例

1> 属性值由多个空格隔开,匹配其中一个值的方法

driver.find_element_by_css_selector("input[class~='btn']")

2> 匹配属性值为字符串开头的方法

driver.find_element_by_css_selector("input[class^='btn']")

3> 匹配属性值字符串结尾的方法

driver.find_element_by_css_selector("input[class$='s_btn']")

 

4> 匹配被 - 分割的属性值的方法, 如上图的 class

driver.find_element_by_css_selector("input[class|='s']")  # 要求精确填写的属性值

三:层级定位

 

 1:E>F    E 下面的 F 这个元素

driver.find_element_by_css_selector('from#form>span>input')#id 是 form 的 form 下面的 span 下面的 input

 

 

2:E:nth-child(n)  如上图,

driver.find_element_by_css_selector('#u_sp > a:nth-child(1)')#id 为 u_sp 的下面的第一个 a 标签。

#实测,这个定位不到,但是方法是对的,- -

3:E:nth-last-child(n),如字面意思:倒数第几个标签

4:E:first-child, 第一个标签

5:E:last-child, 最后一个标签

6:E:only-child, 唯一的标签