Selenium study describes common element positioning method and operation

Reference Address:  https://www.cnblogs.com/eastmount/p/4810690.html

  This article Selenium + common location method Python automated test or reptile in, mouse, keyboard introduction, I hope this article basic articles to help you, if there are errors or deficiencies, please forgive ~ CSDN while total this article is shielded, plus the recently published an article only experts and horses to home (why), which seriously affected the couple's passion for others to read articles and programs ape, so think of your own garden blog account, I feel very good editing features ah, on both sides of the article will be updated later. This last stop recording the first article, I hope to share more articles here!
        Previously directory:
        [Python reptile] installed under Windows PhantomJS and CasperJS and introductory presentation (on)
        [Python reptile] installation PIP + Phantomjs + Selenium in Windows
        [Python reptile] Selenium automatic access to Firefox and Chrome and implement search screenshot
        [Python Reptile ] Selenium automatically log 163 mailboxes and Locating Elements introduced
        [Python reptile] Selenium + Phantomjs dynamic access to information and comments CSDN resources

A positioning method element

        Official website address: http://selenium-python.readthedocs.org/locating-elements.html
        There are various strategies for locating elements of a web page (locate elements), you can choose the most suitable solution, Selenium provides the following method to define the elements of a page:

1
2
3
4
5
6
7
8
find_element_by_id
find_element_by_name
find_element_by_xpath
find_element_by_link_text
find_element_by_partial_link_text
find_element_by_tag_name
find_element_by_class_name
find_element_by_css_selector

        Here it is to find multiple elements (these methods will return a list):

1
2
3
4
5
6
7
find_elements_by_name
find_elements_by_xpath
find_elements_by_link_text
find_elements_by_partial_link_text
find_elements_by_tag_name
find_elements_by_class_name
find_elements_by_css_selector

        In addition to public methods given above, there are also two useful page object locator private methods. These two methods are find_element private and find_elements.
        The method is used by xpath positioned relative path, but also a good CSS method. For example:

Copy the code
<html>
 <body>
  <form id="loginForm">
   <input name="username" type="text" />
   <input name="password" type="password" />
   <input name="continue" type="submit" value="Login" />
   <input name="continue" type="button" value="Clear" />
  </form>
</body>
<html>
Copy the code

        Method username positioning element is as follows:

username = driver.find_element_by_xpath("//form[input/@name='username']")
username = driver.find_element_by_xpath("//form[@id='loginForm']/input[1]")
username = driver.find_element_by_xpath("//input[@name='username']")

        [1] the first element by a form input sub-elements, name attribute and the value achieved username
        [2] found by the first sub-element input id = loginForm form element values
        [3] and a property name is called username the first input element

II. The method of operating elements

        After completion of about locating objects (locate elements) we need to operate on the targeted object, usually all operations will interact with the page by following WebElement interfaces, common operating element method:

1
2
3
4
clear 清除元素的内容
send_keys 模拟按键输入
click 点击元素
submit 提交表单

        For example automatic access to FireFox browser automatically logged 163 mailboxes.

Copy the code
from selenium import webdriver  
from selenium.webdriver.common.keys import Keys  
import time

# Login 163 email
driver = webdriver.Firefox()  
driver.get("http://mail.163.com/")

elem_user = driver.find_element_by_name("username")
elem_user.clear
elem_user.send_keys("15201615157")  
elem_pwd = driver.find_element_by_name("password")
elem_pwd.clear
elem_pwd.send_keys("******")  
elem_pwd.send_keys(Keys.RETURN)
#driver.find_element_by_id("loginBtn").click()
#driver.find_element_by_id("loginBtn").submit()
time.sleep(5)  
assert "baidu" in driver.title  
driver.close()  
driver.quit()  
Copy the code

        First of all by name to locate the user name and password, and then call the method clear () Clears the input box default content, such as "Please enter your password" and other tips by send_keys ( "**") to enter the correct user name and password, and finally through the click () Click login button or send_keys (Keys.RETURN) equivalent to Enter login, submit () submit the form.
        PS: If you need to enter the Chinese to prevent coding errors using send_keys (u "Chinese user name").

Three .WebElement interface to obtain value

        Common values ​​can be obtained by WebElement interfaces, these values ​​are also very important.

1
2
3
4
5
6
7
8
9
10
11
size 获取元素的尺寸
text 获取元素的文本
get_attribute(name) 获取属性值
location 获取元素坐标,先找到要获取的元素,再调用该方法
page_source 返回页面源码
driver.title 返回页面标题
current_url 获取当前页面的URL
is_displayed() 设置该元素是否可见
is_enabled() 判断元素是否被使用
is_selected() 判断元素是否被选中
tag_name 返回元素的tagName

        Example code:

Copy the code
from selenium import webdriver  
from selenium.webdriver.common.keys import Keys  
import time

driver = webdriver.PhantomJS(executable_path="G:\phantomjs-1.9.1-windows\phantomjs.exe")   
driver.get("http://www.baidu.com/")

size = driver.find_element_by_name("wd").size
print size
#尺寸: {'width': 500, 'height': 22}

news = driver.find_element_by_xpath("//div[@id='u1']/a[1]").text
print news
#文本: 新闻

href = driver.find_element_by_xpath("//div[@id='u1']/a[2]").get_attribute('href')
name = driver.find_element_by_xpath("//div[@id='u1']/a[2]").get_attribute('name')
print href,name
#属性值: http://www.hao123.com/ tj_trhao123

location = driver.find_element_by_xpath("//div[@id='u1']/a[3]").location
print location
#坐标: {'y': 19, 'x': 498}

print driver.current_url
#当前链接: https://www.baidu.com/
print driver.title
#标题: 百度一下, 你就知道

result = location = driver.find_element_by_id("su").is_displayed()
print result
#是否可见: True
Copy the code

        其中图片解释如下图所示。

四.鼠标操作

        在现实的自动化测试中关于鼠标的操作不仅仅是click()单击操作,还有很多包含在ActionChains类中的操作。如下:

1
2
3
4
5
6
context_click(elem) 右击鼠标点击元素elem,另存为等行为
double_click(elem) 双击鼠标点击元素elem,地图web可实现放大功能
drag_and_drop(source,target) 拖动鼠标,源元素按下左键移动至目标元素释放
move_to_element(elem) 鼠标移动到一个元素上
click_and_hold(elem) 按下鼠标左键在一个元素上
perform() 在通过调用该函数执行ActionChains中存储行为

        举例如下图所示,获取通过鼠标右键另存为百度图片logo。代码:

Copy the code
import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains

driver = webdriver.Firefox()
driver.get("http://www.baidu.com")

#鼠标移动至图片上 右键保存图片
elem_pic = driver.find_element_by_xpath("//div[@id='lg']/img")
print elem_pic.get_attribute("src")
action = ActionChains(driver).move_to_element(elem_pic)
action.context_click(elem_pic)

#重点:当右键鼠标点击键盘光标向下则移动至右键菜单第一个选项
action.send_keys(Keys.ARROW_DOWN)
time.sleep(3)
action.send_keys('v') #另存为
action.perform()

#获取另存为对话框(失败)
alert.switch_to_alert()
alert.accept()
Copy the code

        效果如下图所示,通过xpath定位到图片位置并右击鼠标,在弹出的菜单中选择“另存为图片”。但是如何点击“另存为对话框”的“保存”按钮是个难点,目前刚学习阶段,境界没到无法解决。原因:
        WebDriver cannot directly interact with dialog windows this is because dialog windows are the domain of the operating system and not the webpage

        该部分推荐参考资料:
         selenium 右键下载图片,结合sikuli - tobecrazy
         Selenium WebDriver 中鼠标和键盘事件分析及扩展
         Selenium Windows Save/Open Open Dialouge - StackOver
        书籍《selenium2 python自动化测试》 作者:虫师

五.键盘操作

        参考:http://selenium-python.readthedocs.org/api.html
        前面讲述了鼠标操作,现在讲述键盘操作。在webdriver的Keys类中提供了键盘所有的按键操作,当然也包括一些常见的组合键操作如Ctrl+A(全选)、Ctrl+C(复制)、Ctrl+V(粘贴)。更多键参考官方文档对应的编码。

1
2
3
4
5
6
7
8
9
10
11
12
send_keys(Keys.ENTER) 按下回车键
send_keys(Keys.TAB) 按下Tab制表键
send_keys(Keys.SPACE) 按下空格键space
send_keys(Kyes.ESCAPE) 按下回退键Esc
send_keys(Keys.BACK_SPACE) 按下删除键BackSpace
send_keys(Keys.SHIFT) 按下shift键
send_keys(Keys.CONTROL) 按下Ctrl键
send_keys(Keys.ARROW_DOWN) 按下鼠标光标向下按键
send_keys(Keys.CONTROL,'a') 组合键全选Ctrl+A
send_keys(Keys.CONTROL,'c') 组合键复制Ctrl+C
send_keys(Keys.CONTROL,'x') 组合键剪切Ctrl+X
send_keys(Keys.CONTROL,'v') 组合键粘贴Ctrl+V

        这里使用的例子参考虫师的书籍《selenium2 python自动化测试》,推荐该书给大家。代码还是非常有意思的,大家自己去感受下吧~

Copy the code
#coding=utf-8
import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
driver.get("http://www.baidu.com")

#输入框输入内容
elem = driver.find_element_by_id("kw")
elem.send_keys("Eastmount CSDN")
time.sleep(3)

#删除一个字符CSDN 回退键
elem.send_keys(Keys.BACK_SPACE)
elem.send_keys(Keys.BACK_SPACE)
elem.send_keys(Keys.BACK_SPACE)
elem.send_keys(Keys.BACK_SPACE)
time.sleep(3)

#输入空格+"博客"
elem.send_keys(Keys.SPACE)
elem.send_keys(u"博客")
time.sleep(3)

#ctrl+a 全选输入框内容
elem.send_keys(Keys.CONTROL,'a')
time.sleep(3)

Cut # ctrl + x content input box 
elem.send_keys (Keys.CONTROL, 'X') 
the time.sleep (. 3) 

# re-enter the search input box 
elem.send_keys (Keys.CONTROL, 'V') 
the time.sleep (. 3 ) 

# replace by the Enter key clicks 
driver.find_element_by_id ( "su"). send_keys (Keys.ENTER) 
the time.sleep (3) 

driver.quit ()

Guess you like

Origin www.cnblogs.com/xumBlog/p/10992721.html