selenium-页面操作

1 web

1.1 简单介绍

Web应用程序的测试工具很多种,关于web前端技术如HTML,JS,CSS等的基础知识本文不作介绍,本节只介绍selenium工具在web应用程序自动化测试中的简单应用。

1.1.1 准备工作

[1].          安装pip

说明:见3 环境搭建

[2].          安装selenium

说明:pip install selenium

[3].           安装chrome.exe浏览器

说明:推荐版本 63.0.3239.84(正式版本)(32 位)

[4].          准备chromedriver2.33.exe

说明:存放在resource\tools\chromedriver2.33.exe,程序使用,不需要手动特别安装。

1.2 快速入门

 1 from selenium import webdriver
 2 from selenium.webdriver.support.select import Select
 3 
 4 def refresh(brower, trytimes=10):
 5     """
 6     Sometimes, the element actually exits and the way we locate is right,
 7     but there still raises exception like "cannot locate element"; the root
 8     cause not found; this function is a temperoary way to fix it.
 9     """
10     try:
11         all_div = brower.find_elements_by_tag_name("div")
12         all_td = brower.find_elements_by_tag_name("td")
13         for div in all_div:
14             logging.debug(div.get_attribute("id"))
15         for td in all_td:
16             logging.debug(td.get_attribute("id"))
17     except Exception as e:
18         logging.debug(e)
19         if (trytimes > 0):
20             refresh(trytimes - 1)
21         else:
22             raise ValueError
23 
24 #打开chrome浏览器,并带着http://admin:90123456@192.168.1.1请求加载web页面
25 #reates a new instance of the chrome driver.
26 b = webdriver.Chrome(r"D:\auto test\Together_v0.2\resource\tools\chromedriver2.33.exe")
27 #Loads a web page in the current browser session.
28 b.get("http://admin:90123456@192.168.1.1")
29 b.get("http://192.168.1.1") # sugget one more try.
30 
31 #Switches focus to the specified frame, by index, name, or webelement.
32 b.switch_to.frame("fInfo")
33 
34 #依次点击Features -> ACL, 转到ACL控制页面
35 #Finds an element by xpath. && Clicks the element.
36 b.find_element_by_xpath("//*[@id=\"menu\"]/ul/li[3]").click() #click Features
37 b.find_element_by_xpath("//*[@id=\"menu\"]/ul/li[3]/ul/li[3]/a").click() #click Features -> ACL
38 
39 # suggest wait seconds after enter another page.
40 import time
41 time.sleep(7)
42 
43 # temporary way to fix exception "cannot locate element".
44 refresh(b)
45 
46 #设置ACL Rule Index旁边的下拉框为可见,只有可见之后,才能用Select库的相关选择函数。
47 #Synchronously Executes JavaScript in the current window/frame.
48 b.execute_script('document.getElementById("RuleIndexSEL").style.display="block";')  #Features >> ACL , set select "ACL Rule Index" can be seen.
49 #选择ACL Rule Index旁边的下拉框为3
50 # for SELECT tag, select an option <option value="2">3</option>
51 Select(b.find_element_by_id("RuleIndexSEL")).select_by_value('2') #Features >> ACL ,  select option 3 in select "ACL Rule Index"
52 
53 #点击Active旁边的按钮,设置为enable
54 #Finds an element by id. && Clicks the element.
55 b.find_element_by_id("RuleActiveRDO").click() #Features >> ACL , click "Active" to enable
56 
57 #设置Interface旁边的下拉框为可见
58 b.execute_script('document.getElementById("InterfaceSEL").style.display="block";') #Features >> ACL ,set select "Interface" can be seen.
59 #选择Interface旁边的下拉框的选项为LAN
60 # for SELECT tag, select an option <option value="LAN">LAN</option>
61 Select(b.find_element_by_id("InterfaceSEL")).select_by_value("LAN") #Features >> ACL , elect option LAN in select "Interface"
62 
63 #点击SET按钮,保存页面的配置。
64 b.find_element_by_xpath("//*[@id=\"rightFunc\"]/li[4]/div[1]").click() #Features >> ACL , click "SET" button to save settings.
65 
66 #关闭页面
67 b.close()

1.3 代码解释

1.3.1 初始化

需要先导入相关类库,导入方法如下:

from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.support.select import Select

 
实例化一个类WebDriver类,实例方法如下,参数是chromedriver的路径:

e.g: browser = webdriver.Chrome("resource\tools\chromedriver2.33.exe")

 

该函数参数详细介绍:

    webdriver.Chrome(executable_path="chromedriver", port=0,

                 chrome_options=None, service_args=None,

                 desired_capabilities=None, service_log_path=None):

        """

        Creates a new instance of the chrome driver.

 

        Starts the service and then creates new instance of chrome driver.

 

        :Args:

         - executable_path - path to the executable. If the default is used it assumes the executable is in the $PATH

         - port - port you would like the service to run, if left as 0, a free port will be found.

         - desired_capabilities: Dictionary object with non-browser specific

           capabilities only, such as "proxy" or "loggingPref".

         - chrome_options: this takes an instance of ChromeOptions

        """

1.3.2 加载页面

打开浏览器并加载指定url时,使用get(url函数

e.g: brower.get("http://loginName@loginPasword@192.168.1.1")
e.g: brower.get("http://192.168.1.1")

 

该函数参数详细介绍:

    browser.get(url):

        """

        Loads a web page in the current browser session.

        """

1.3.3 元素定位

定位元素的目的是为了改变或者获取元素的相关信息,在定位到指定元素之后,才可以对其执行点击鼠标、拖动鼠标等操作。元素定位的方法比较多也比较丰富,本节指出几个常用的定位方法。使用的例子依据的html源码如下图所示。关于selenium的元素定位的函数的详细介绍见 [附录A.2.1 find_elemet(s)_XXX]

 

 

 

 

 

 

通过XPath定位获取text为”LAN”的td元素 (关于XPath的获取参见[附录B.1])

element = browser.find_element_by_xpath("//*[@id=\"main\"]/table/tbody/tr/td[5]")
elements = browser.find_elements_by_xpath("//*[@id=\"main\"]/table/tbody/tr/td[5]")

 

find_element_XXXX(…) 与 find_elements_XXX(…)函数的参数及意义是一样的。区别在于它们的返回值,前者是返回一个element,后者是返回一个element列表;

 

通过id定位获取id值为RuleActiveRDO_ck的元素

element=browser.find_element_by_id("RuleActiveRDO_ck")

 

通过name定位获取name值为RuleActiveRDO_ck的元素

element=browser.find_element_by_name("RuleActiveRDO_ck")

 

通过tag_name定位获取td元素(tag_name指标签名称)

element=browser.find_element_by_tag_name("td")

 

通过class_name定位class值为mainTable的table元素

element=browser.find_element_by_class_name("mainTable")

1.3.4 元素信息

获取element的属性值

element = browser.find_element_by_id("InterfaceSEL")
val = element.get_attribute("id")   # InterfaceSEL
val = element.get_attribute("name") # InterfaceSEL
val = element.get_attribute("sb") # 30512517
val = element.get_attribute("style") # display: none;

 

获取element的标签名称

element = browser.find_element_by_id("InterfaceSEL")

val = element.tag_name # select

 

获取element的文本框

element=browser.find_element_by_xpath("//*[@id=\"main\"]/table/tbody/tr/td[5]")
val = element.text # LAN

 

查看元素对用户是否可见

val = element.is_displayed() #True of False

 

查看元素是否被选中,比如可检查checkbox或radio按钮是否被选中

val = element.is_selected() #True of False

 

获取浏览器当前url

val = browser.current_url

 

获取当前页面的源码

val = browser.page_source

1.3.5 动作事件

获取到element元素后,可以对元素执行鼠标、键盘甚至执行script脚本等动作事件。本节介绍本人已知的并且经常用到的几个方法。

(一) WebDriver

在当前的window/frame中执行一段JaveScript脚本,比如下面这条语句是将id为InterfaceSEL的select元素由不可见变成可见:

browser = webdriver.Chrome(r"resource\tools\chromedriver2.33.exe")

browser.execute_script('document.getElementById("InterfaceSEL").style.display="block";'

执行之前:

 

执行之后

 

 

如下语句效果是等同的。

browser.execute_script(‘'document.getElementById("hid_password").value = "admin";’)

browser.find_element_by_id("hid_password").send_keys("admin")

 

浏览器的历史记录中,退回到上一个页面

browser.back()

 

浏览器的历史记录中,前进到下一个页面

browser.forward()

 

页面刷新,同按F5效果类似

browser.refresh()

 

关于frame;在html页面中,存在着用frame标签嵌套另一个html页面的情况,如下面的名为debug.html的页面的源代码如下,在debug.html中又嵌套了两个frame, 其中一个frame的name属性为”finfo”, 如果要控制name=”fInfo”中的元素如id=”test”的input, 需要先把控制焦点转到fInfo的frame上。

 

转到特定frame:browser.switch_to.frame("fInfo")

回到默认frame:brower.switch_to.default_content()

 

debug.html

 

<html>

<frame name="fPanel" src="" scrolling="auto" marginwidth="0" marginheight="0">

         <html><head></head><body marginwidth="0" marginheight="0"></body></html>

</frame>

<frame name="fInfo" src="/cgi-bin/New_GUI/Home.asp">

         <html><input id="test"/></html>

</frame>

</html>

(二) WebElement

单击元素

element = browser.find_element_by_id("RuleActiveRDO_ck")
element.click()

 

清除文本,通常用于情况文本输入框的内容。

element = browser.find_element_by_name("fname")
element.clear()

 

在元素上模拟按键输入

element = browser.find_element_by_name("lname")
element.send_keys("auto test lname")

(三)Select标签

在对select标签运用selenium.webdriver.support.select之前,需要先使该标签对用户是可见的,设置方法见1.3.5 (一),在selenium.webdriver中关于select标签的操作由Select提供。

导入:from selenium.webdriver.support.select import Select

 

 

 

#选中WAN_Option
Select(element).select_by_value("WAN")

#选中LAN_Option
Select(element).select_by_index(1)

(四)ActionChains

在selenium.webdriver中关于鼠标的操作由ActionChains提供。

 

导入:from selenium.webdriver import ActionChains

 

常用的方法有

move_to_element(to_element):鼠标悬停,有些菜单需要鼠标停在该位置处,才能出现下拉菜单。

double_click(on_element=None):在指定元素或者当前位置处双击鼠标

click(on_element=None): 在指定元素或者当前位置处单击鼠标

context_click(on_element=None): 在指定元素或者当前位置处右击鼠标

 

以上四个动作都需要调用perform()才会被执行。

 

以下是几个使用例子:

from selenium import webdriver
from selenium.webdriver import ActionChains

browser = webdriver.Chrome(r"D:\auto test\Together_v0.2\resource\tools\chromedriver2.33.exe")
browser.get("file:///C:/Users/20002106/Desktop/temp/auto-test.html")

#定位到提交按钮元素
element = browser.find_element_by_xpath("/html/body/div[2]/form/input[3]")
#将鼠标悬停在提交按钮
ActionChains(browser).move_to_element(element).perform()
#在提交按钮处双击
ActionChains(browser).double_click(element).perform()
#在提交按钮处单击
ActionChains(browser).click(element).perform()
#在提交按钮处右击鼠标
ActionChains(browser).context_click(element).perform()

1.3.6 断开连接

需要关闭当前窗口并退出chrome浏览器时,可用quit()和close()中的任何一个函数。

e.g browser.quit()
e.g browser.close()

函数参数详细介绍

 browser.close():

        """

        Closes the current window.

 

        :Usage:

            driver.close()

        """

 

browser.quit():

        """

        Quits the driver and closes every associated window.

 

        :Usage:

            driver.quit()

        """

1.4 Reference

[1].          http://www.selenium.org

A.2 webdriver

A.2.1 find_element(s)_XXX

  1  def webdriver.find_element_by_id(id_):
  2 
  3         """Finds an element by id.
  4 
  5  
  6 
  7         :Args:
  8 
  9          - id\_ - The id of the element to be found.
 10 
 11  
 12 
 13         :Usage:
 14 
 15             driver.find_element_by_id('foo')
 16 
 17         """
 18 
 19         
 20 
 21     webdriver.find_elements_by_id(id_):
 22 
 23         """
 24 
 25         Finds multiple elements by id.
 26 
 27  
 28 
 29         :Args:
 30 
 31          - id\_ - The id of the elements to be found.
 32 
 33  
 34 
 35         :Usage:
 36 
 37             driver.find_elements_by_id('foo')
 38 
 39         """
 40 
 41         
 42 
 43     webdriver.find_element_by_xpath(xpath):
 44 
 45         """
 46 
 47         Finds an element by xpath.
 48 
 49  
 50 
 51         :Args:
 52 
 53          - xpath - The xpath locator of the element to find.
 54 
 55  
 56 
 57         :Usage:
 58 
 59             driver.find_element_by_xpath('//div/td[1]')
 60 
 61         """
 62 
 63         
 64 
 65     webdriver.find_elements_by_xpath(xpath):
 66 
 67         """
 68 
 69         Finds multiple elements by xpath.
 70 
 71  
 72 
 73         :Args:
 74 
 75          - xpath - The xpath locator of the elements to be found.
 76 
 77  
 78 
 79         :Usage:
 80 
 81             driver.find_elements_by_xpath("//div[contains(@class, 'foo')]")
 82 
 83         """
 84 
 85         
 86 
 87     webdriver.find_element_by_link_text(link_text):
 88 
 89         """
 90 
 91         Finds an element by link text.
 92 
 93  
 94 
 95         :Args:
 96 
 97          - link_text: The text of the element to be found.
 98 
 99  
100 
101         :Usage:
102 
103             driver.find_element_by_link_text('Sign In')
104 
105         """
106 
107         
108 
109     webdriver.find_elements_by_link_text(text):
110 
111         """
112 
113         Finds elements by link text.
114 
115  
116 
117         :Args:
118 
119          - link_text: The text of the elements to be found.
120 
121  
122 
123         :Usage:
124 
125             driver.find_elements_by_link_text('Sign In')
126 
127         """
128 
129         
130 
131     webdriver.find_element_by_partial_link_text(link_text):
132 
133         """
134 
135         Finds an element by a partial match of its link text.
136 
137  
138 
139         :Args:
140 
141          - link_text: The text of the element to partially match on.
142 
143  
144 
145         :Usage:
146 
147             driver.find_element_by_partial_link_text('Sign')
148 
149         """
150 
151         
152 
153     webdriver.find_elements_by_partial_link_text(link_text):
154 
155         """
156 
157         Finds elements by a partial match of their link text.
158 
159  
160 
161         :Args:
162 
163          - link_text: The text of the element to partial match on.
164 
165  
166 
167         :Usage:
168 
169             driver.find_element_by_partial_link_text('Sign')
170 
171         """
172 
173         
174 
175     webdriver.find_element_by_name(name):
176 
177         """
178 
179         Finds an element by name.
180 
181  
182 
183         :Args:
184 
185          - name: The name of the element to find.
186 
187  
188 
189         :Usage:
190 
191             driver.find_element_by_name('foo')
192 
193         """
194 
195         
196 
197     webdriver.find_elements_by_name(self, name):
198 
199         """
200 
201         Finds elements by name.
202 
203  
204 
205         :Args:
206 
207          - name: The name of the elements to find.
208 
209  
210 
211         :Usage:
212 
213             driver.find_elements_by_name('foo')
214 
215         """
216 
217         
218 
219     webdriver.find_element_by_tag_name(name):
220 
221         """
222 
223         Finds an element by tag name.
224 
225  
226 
227         :Args:
228 
229          - name: The tag name of the element to find.
230 
231  
232 
233         :Usage:
234 
235             driver.find_element_by_tag_name('foo')
236 
237         """
238 
239         
240 
241     webdriver.find_elements_by_tag_name(name):
242 
243         """
244 
245         Finds elements by tag name.
246 
247  
248 
249         :Args:
250 
251          - name: The tag name the use when finding elements.
252 
253  
254 
255         :Usage:
256 
257             driver.find_elements_by_tag_name('foo')
258 
259         """
260 
261         
262 
263     webdriver.find_element_by_class_name(name):
264 
265         """
266 
267         Finds an element by class name.
268 
269  
270 
271         :Args:
272 
273          - name: The class name of the element to find.
274 
275  
276 
277         :Usage:
278 
279             driver.find_element_by_class_name('foo')
280 
281         """
282 
283         
284 
285     webdriver.find_elements_by_class_name(name):
286 
287         """
288 
289         Finds elements by class name.
290 
291  
292 
293         :Args:
294 
295          - name: The class name of the elements to find.
296 
297  
298 
299         :Usage:
300 
301             driver.find_elements_by_class_name('foo')
302 
303         """
304 
305         
306 
307     webdriver.find_element_by_css_selector(css_selector):
308 
309         """
310 
311         Finds an element by css selector.
312 
313  
314 
315         :Args:
316 
317          - css_selector: The css selector to use when finding elements.
318 
319  
320 
321         :Usage:
322 
323             driver.find_element_by_css_selector('#foo')
324 
325         """
326 
327         
328 
329     webdriver.find_elements_by_css_selector(css_selector):
330 
331         """
332 
333         Finds elements by css selector.
334 
335  
336 
337         :Args:
338 
339          - css_selector: The css selector to use when finding elements.
340 
341  
342 
343         :Usage:
344 
345             driver.find_elements_by_css_selector('.foo')
346 
347         """
find_elements_XXX

 

posted on 2020-04-21 16:37  LiveWithACat  阅读(403)  评论(0编辑  收藏  举报