Selenium操作Web
简介
webUI自动化工具–selenium
原理:代码利用浏览器驱动(browser driver)间接来控制浏览器被测页面
具体点就是利用webdriver协议来控制
主要浏览器:IE,谷歌,火狐;需要浏览器对应的驱动
环境搭建:
1.准备测试库(python)-- pip install selenium
2.浏览器驱动:http://npm.taobao.org/mirrors/chromedriver/
添加环境变量:D:\tools\chromedriver
webUI自动化套路
1.选择元素:根据目标元素特征定位
2.操作元素:点击,输入,拖拽等
要进行这些操作,需要稍微了解一下html
设置下载路径
chromePath = ".\webdriver\chromedriver.exe"
autoDownloadsPath="D:\AutoDownloads"
options = webdriver.ChromeOptions()
prefs = {"download.default_directory": autoDownloadsPath,}
options.add_experimental_option('prefs', prefs)
driver = webdriver.Chrome(executable_path=chromePath, options=options)
一、元素定位
1.id定位
可以根据元素的id来定位属性,id是当前整个HTML页面中唯一的,所以可以通过id属性来唯一定位一个元素,是首选的元素定位方式。(动态ID不做考虑)
self.driver.find_element_by_id()
2.name定位
根据元素的name来定位属性,但name并不是唯一的。
self.driver.find_element_by_name()
3.class name定位
根据Class定位属性,主要是用来元素进行分组,并对这一级元素设置相同的样式。所以class属性在当前html页面当中,也是不能唯一定位到一个元素的,class的属性只有一个值。
self.driver.find_element_by_class_name()
4.tag name定位
通过元素的标签名来定位元素,如:input标签、span标签
self.driver.find_element_by_tag_name()
5.link_text和partial_link_text定位
link_text和partial_link_text是作用于链接a标签的,link_text用于全部匹配文本值,partial_link_text用于部分匹配文本值。
self.driver.find_element_by_link_text()
self.driver.find_element_by_partial_link_text()
6.css定位
通过组合的方式进行定位,和XPATH定位方式基本相同。
self.driver.find_element_by_css_selector()
7.xpath定位
xpath定位分为绝对定位和相对定位
self.driver.find_element_by_xpath()
二、灵活的xpath
1.亲属关系匹配
通常我们把节点之间的归属关系归结为一种亲属关系,如父亲、孩子、祖先、后代、兄弟等等。在对元素进行匹配时,同样可以用到这些概念。例如:
//E/parent::* 表示所有E节点的父节点元素
//F/ancestor::* 表示所有F元素的祖先节点元素
/A/child::* 表示A的子元素
/A/descendant::* 表示A的所有后代元素
//F/self::* 表示所有F的自身元素
//F/ancestor-or-self::* 表示所有F元素及它的祖先节点元素
/A/C/descendant-or-self::* 表示所有A元素→C元素及它们的后代元素
/A/C/following-sibling::* 表示A元素→C元素的紧邻的后序所有兄弟节点元素
/A/C/preceding-sibling::* 表示A元素→C元素的紧邻的前面所有兄弟节点元素
/A/B/C/following::* 表示A元素→B元素→C元素的后序的所有元素
/A/C/preceding::* 表示A元素→C元素的前面的所有元素
2.selenium使用Xpath定位之完整篇
第一种方法:通过绝对路径做定位
self.driver.find_element_by_xpath("/html/body/div/form/input")
第二种方法:通过相对路径做定位
self.driver.find_element_by_xpath("//input")
第三种方法:使用xpath属性定位
self.driver.find_element_by_xpath("//input[@id='id']")
self.driver.find_element_by_xpath("//input[@class='class' and @id='id']")
第四种方法:使用部分属性值匹配
self.driver.find_element_by_xpath("//text()[start-with(.,'从前面匹配')]")
self.driver.find_element_by_xpath("//text()[ends-with(.,'从后面匹配')]")
self.driver.find_element_by_xpath("//text()[contains(.,'关键字匹配')]")
三、强大的js
1.点击元素
第一种点击方式:
button = self.driver.find_element_by_xpath('//*[@class="mask-dark"]')
self.driver.execute_script("$(arguments[0]).click()",button)
第二种点击方式:
button = 'document.querySelector("body > div.mask-dark").click()'
self.driver.execute_script(button)
2.修改属性
修改元素属性
button = self.driver.find_element_by_xpath('//*[@class="mask-dark"]')
self.driver.execute_script('arguments[0].class="aaa;"',button)
删除元素属性
button = self.driver.find_element_by_xpath('//*[@class="mask-dark"]')
self.driver.execute_script('arguments[0].removeAttribute(\"class\")', button)