代码改变世界

selenium python bindings 元素定位

2016-07-22 15:46  chercher  阅读(322)  评论(0编辑  收藏  举报

1. 辅助 Firepath

Firefox是所有做前端的必不可少的浏览器因为firebug的页面元素显示很清晰。用selenium 去定位元素的时候Firefox还有一个非常友好的工具就是firepath。下载firepath,点击页面元素选择firepath选项,就会给出一种找到元素的路径。

可以选择的方式有xPath、sizzleJS、css三种方法。

a.sizzle没有用过,由于过于麻烦还refactor过一个job改掉sizzle的定位方式。

b.xPath肯定会找到这个元素且没有遇到重复的现象,但是这个路径可能会过长。

c.css则会因前端页面的写法不同而不一定能找到对应的。

所以这是个参考的方式,如果无明确的id或者class可以先用firepath 的xPath定位下然后化繁为简比较不容易出错。

 

定位的方式和写法很多,不一一都再举例子,参考下selenium python bindings的网站,然后找几个例子逆向推出如果能搞清楚对应的页面结构就完事儿了~给些示例供以后参考

 

2. xPath

textArea_script = driver.find_element_by_xpath("//div[@class='CodeMirror']/div/textarea")

textArea_script = driver.find_element_by_xpath("//*[@class='CodeMirror']/div/textarea")

textArea_script = driver.find_element_by_xpath("//textarea[contains(text(), 'text')]")

textArea_script = driver.find_element_by_xpath("//*[contains(text(), 'text')]")

这四种其实都能找到同一个元素

 

next = x("//input[@value = '下一步']")

edit_next = x("//input[@name = 'detail_subject_submit']")

 

3. class&id

最简单的定位方法,只需要知道class用. id用#的区别就可以了(依赖自己写的方法)~平常还是用find_element_by_class/id 就可以

login_form = driver.find_element_by_id('loginForm')

content = driver.find_element_by_class('content')

 

4. 其他

还有很多关于Link text或者tag等等的定位方法,使用频度较低,必须使用的时候再找官网例子即可~