[Python crawler] Introduction to the method and operation of common element localization in selenium

Source: Internet
Author: User
Tags delete key xpath

This article mainly Selenium+python automatic test or crawler in the common positioning methods, mouse operation, keyboard operation introduced, I hope that the basic article on your help, if there are errors or shortcomings, please Haihan ~
Previous directory:
[python crawler] install PHANTOMJS and Casperjs in Windows and introduction (top)
[Python crawler] installs pip+phantomjs+selenium under Windows
[Python crawler] Selenium automatically access Firefox and chrome for search
[Python crawler] Selenium Implementation Automatic login 163 mailbox and locating elements Introduction
[Python crawler] SELENIUM+PHANTOMJS dynamic Get csdn Download resource information and comments

I. Positioning element methods
Website address: http://selenium-python.readthedocs.org/locating-elements.html
Here are a variety of strategies for locating elements in a Web page (locate elements), you can choose the most appropriate scenario, selenium provides a way to define the elements of a page:
    • 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's how to find multiple elements (these methods will return a list):

    • 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 the public methods given above, there are two private methods that are useful in the Page object locator. These two private methods are find_element and find_elements.
The common method is to use the XPath relative path to locate, and CSS is a better method. Example:

[HTML]View PlainCopy
  1. <html>
  2. <body>
  3. <form id="LoginForm">
  4. <input name="username" type= "text" />
  5. <input name="password" type="password" />
  6. <input name="Continue" type= "submit" value="Login" />
  7. <input name="Continue" type= "button" value="Clear" />
  8. </form>
  9. </body>
  10. <html>

Here's how to locate the username element:

[Python]View PlainCopy
    1. Username = Driver.find_element_by_xpath ("//form[input/@name = ' username ']")
    2. Username = Driver.find_element_by_xpath ("//form[@id = ' loginform ']/input[1]")
    3. Username = Driver.find_element_by_xpath ("//input[@name = ' username ']")

[1] The first FORM element is implemented by an input child element, the Name property and the value username
[2] The first input child element is found by a form element of the Id=loginform value
[3] The first INPUT element with the name of the property named name and a value of username

Two. Operation Element method

After describing the anchored object (locate elements) we need to manipulate the anchored object, usually all the operations and page interaction will pass through the Webelement interface, the common operation element method is as follows:

    • Clear clears the contents of an element
    • Send_keys Analog Key input
    • Click on the element
    • Submit Form

For example, automatic access to Firefox browser automatically login 163 mailbox.

[Python]View PlainCopy
  1. From Selenium import Webdriver
  2. From Selenium.webdriver.common.keys import keys
  3. Import time
  4. # Login 163 Email
  5. Driver = Webdriver. Firefox ()
  6. Driver.get ("http://mail.163.com/")
  7. Elem_user = Driver.find_element_by_name ("username")
  8. Elem_user.clear
  9. Elem_user.send_keys ("15201615157")
  10. Elem_pwd = driver.find_element_by_name ("password")
  11. Elem_pwd.clear
  12. Elem_pwd.send_keys ("******")
  13. Elem_pwd.send_keys (Keys.return)
  14. #driver. find_element_by_id ("Loginbtn"). Click ()
  15. #driver. find_element_by_id ("Loginbtn"). Submit ()
  16. Time.sleep (5)
  17. Assert "Baidu" in driver.title
  18. Driver.close ()
  19. Driver.quit ()

First locate the user name and password by name, then call the method Clear () Clear the Input box default content, such as "Please enter password" and other prompts, through Send_keys ("* *") enter the correct user name and password, and finally through Click () Click the login button or Send_keys ( Keys.return) is equivalent to a carriage return login, submit () Submission form.
PS: If you need to input Chinese, prevent encoding error using Send_keys (U "Chinese user name").

Three. Webelement interface Get value

Common values can be obtained through the Webelement interface, which is equally important.

    • Size gets the dimensions of the element
    • Text gets the literal of the element
    • Get_attribute (name) Gets the property value
    • Location gets the element coordinates, first finds the element to get, and then calls the method
    • Page_source back to page source code
    • Driver.title return page title
    • Current_url gets the URL of the current page
    • Is_displayed () sets whether the element is visible
    • Is_enabled () Determine if the element is being used
    • Is_selected () Determines whether the element is selected
    • Tag_name returns the tagname of the element

The example code is as follows:

[Python]View PlainCopy
  1. From Selenium import Webdriver
  2. From Selenium.webdriver.common.keys import keys
  3. Import time
  4. Driver = Webdriver. PHANTOMJS (executable_path="G:\phantomjs-1.9.1-windows\phantomjs.exe")
  5. Driver.get ("http://www.baidu.com/")
  6. Size = Driver.find_element_by_name ("WD"). Size
  7. Print size
  8. #尺寸: {' width ': $, ' height ': 22}
  9. News = Driver.find_element_by_xpath ("//div[@id = ' U1 ']/a[1]"). Text
  10. Print News
  11. #文本: News
  12. href = Driver.find_element_by_xpath ("//div[@id = ' U1 ']/a[2]"). Get_attribute (' href ')
  13. Name = Driver.find_element_by_xpath ("//div[@id = ' U1 ']/a[2]"). Get_attribute (' name ')
  14. Print Href,name
  15. #属性值: http://www.hao123.com/tj_trhao123
  16. Location = Driver.find_element_by_xpath ("//div[@id = ' U1 ']/a[3]"). location
  17. Print location
  18. #坐标: {' y ': +, ' x ': 498}
  19. Print Driver.current_url
  20. #当前链接: https://www.baidu.com/
  21. Print Driver.title
  22. #标题: Baidu a bit, you know
  23. result = Location = driver.find_element_by_id ("su"). is_displayed ()
  24. Print result
  25. #是否可见: True

Where the picture is interpreted as shown.



Four. Mouse operation

In real-world automated tests, the mouse operation is more than just click (), and there are many operations included in the Actionchains class. As follows:

    • Context_click (Elem) Right click on the mouse click on the element Elem, save as behavior
    • Double_click (elem) Double click the mouse click on the element Elem, the map Web can achieve amplification function
    • Drag_and_drop (source,target) Drag the mouse, the source element press the left key to move to the target element release
    • Move_to_element (Elem) mouse moves to an element
    • Click_and_hold (Elem) Press the left mouse button on an element
    • Perform () performs the stored behavior in Actionchains by calling the function

For example, get the right mouse button saved as Baidu image logo. Code:

[Python]View PlainCopy
  1. Import time
  2. From Selenium import Webdriver
  3. From Selenium.webdriver.common.keys import keys
  4. From Selenium.webdriver.common.action_chains import actionchains
  5. Driver = Webdriver. Firefox ()
  6. Driver.get ("http://www.baidu.com")
  7. #鼠标移动至图片上 right-click to save a picture
  8. Elem_pic = Driver.find_element_by_xpath ("//div[@id = ' lg ']/img")
  9. Print Elem_pic.get_attribute ("src")
  10. Action = Actionchains (Driver). Move_to_element (Elem_pic)
  11. Action.context_click (Elem_pic)
  12. #重点: Move to the right-click menu First option when right mouse clicks the keyboard cursor down
  13. Action.send_keys (Keys.arrow_down)
  14. Time.sleep (3)
  15. Action.send_keys (' V ') #另存为
  16. Action.perform ()
  17. #获取另存为对话框 (FAILED)
  18. Alert.switch_to_alert ()
  19. Alert.accept ()

As shown in the effect, navigate to the picture position with XPath and right-click the mouse and select "Save as Picture" in the pop-up menu. But how to click on the "Save As Dialog" button is a difficult, at present, just learning stage, the realm has not been able to solve. Reason:
Webdriver cannot directly interact with dialog Windows this was because dialog windows is the domain of the operating Syst Em and not the webpage.


This section recommends reference materials:
Selenium right-click Download image, combined with Sikuli-tobecrazy
Analysis and extension of mouse and keyboard events in Selenium Webdriver
Selenium Windows Save/open Open dialouge-stackover
Book "Selenium2 python Automation test" bug Master

Five. Keyboard operation

Reference: http://selenium-python.readthedocs.org/api.html
The mouse operation is described earlier and the keyboard operation is now described. All keyboard keystrokes are provided in the keys class of Webdriver, and of course include some common key combinations such as CTRL + A (select all), CTRL + C (copy), and Ctrl + V (paste). More keys refer to the encoding for the official documentation.

    • Send_keys (keys.enter) Press ENTER
    • Send_keys (Keys.tab) Press the Tab tab
    • Send_keys (Keys.space) Press the space bar space
    • Send_keys (Kyes.escape) Press the REWIND key ESC
    • Send_keys (keys.back_space) Press the DELETE key backspace
    • Send_keys (Keys.shift) Press the SHIFT key
    • Send_keys (Keys.control) hold down the CTRL key
    • Send_keys (Keys.arrow_down) Press the mouse cursor down button
    • Send_keys (Keys.control, ' a ') key combination all Select Ctrl + A
    • Send_keys (Keys.control, ' C ') key combination copy Ctrl + C
    • Send_keys (Keys.control, ' x ') combined key shear Ctrl+x
    • Send_keys (Keys.control, ' V ') bonding Ctrl + V

The examples used here refer to the insect Master's book "Selenium2 Python Automation Test", which is recommended for everyone. Code is very interesting, we have to feel the next ~

[Python]View PlainCopy
    1. #coding =utf-8
    2. Import time
    3. From Selenium import Webdriver
    4. From Selenium.webdriver.common.keys import keys
    5. Driver = Webdriver. Firefox ()
    6. Driver.get ("http://www.baidu.com")
    7. #输入框输入内容
    8. Elem = driver.find_element_by_id ("kw")
    9. Elem.send_keys ("Eastmount CSDN")
    10. Time.sleep (3)
    11. #删除一个字符CSDN fallback key
    12. Elem.send_keys (Keys.back_space)
    13. Elem.send_keys (Keys.back_space)
    14. Elem.send_keys (Keys.back_space)
    15. Elem.send_keys (Keys.back_space)
    16. Time.sleep (3)
    17. #输入空格 + "Blog"
    18. Elem.send_keys (Keys.space)
    19. Elem.send_keys (U"blog")
    20. Time.sleep (3)
    21. #ctrl +a Select all input Box contents
    22. Elem.send_keys (Keys.control,' a ')
    23. Time.sleep (3)
    24. #ctrl +x cut Input Box contents
    25. Elem.send_keys (Keys.control,' x ')
    26. Time.sleep (3)
    27. #输入框重新输入搜索
    28. Elem.send_keys (Keys.control,' V ')
    29. Time.sleep (3)
    30. #通过回车键替代点击操作
    31. driver.find_element_by_id ("su"). Send_keys (Keys.enter)
    32. Time.sleep (3)
    33. Driver.quit ()

[Python crawler] Introduction to the method and operation of common element localization in selenium

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.