Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Selenium in python Automation Test

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

Editor to share with you how to use Selenium in python automation testing, I believe most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!

1. Installation

To complete the automated test, you need to configure three things.

Selenium:pip is fine.

Chrome: just download a Google browser from the browser

Chrome-driver: download address http://chromedriver.storage.googleapis.com/index.html

After downloading from the browser to the local mac, it is automatically saved to the Download/ directory on the local Download/.

But we need to move it where it's supposed to be.

The specific terminal commands are as follows:

# directory to the download location cd Downloads/# extract the zip file unzip chromedriver_mac64.zip # after getting the extracted file Unix Executable type file, move it to the location mv chromedriver / usr/local/bin/2. Basic operation

Let's take a look at some of the basic operations of Selenium. First write a few simple small functions to demonstrate:

From selenium import webdriverfrom selenium.webdriver.common.keys import Keysbrowser = webdriver.Chrome () browser.get ('https://www.baidu.com')input = browser.find_element_by_id (' kw') input.send_keys ('Yang Mi') input.send_keys (Keys.ENTER) print (browser.current_url) print (browser.get_cookies ()) print (browser.page_source)

When you run the above code, you can see that a Chrome browser pops up automatically, and it says: Chrome is being controlled by automatic software. Then open Baidu and type "Yang Mi" in the input box to search.

2.1 declare browser objects

Selenium supports many browsers, such as:

From selenium import webdriver# declares the browser object and requires the corresponding driver to use browser = webdriver.android () browser = webdriver.blackberry () browser = webdriver.chrome () browser = webdriver.edge () browser = webdriver.firefox () browser = webdriver.ie () browser = webdriver.opera () browser = webdriver.phantomjs () browser = webdriver.safari ()

I can see that there are IE browsers, Edge browsers, FireFox browsers, Opera browsers, and so on.

2.2 visit the web page

You can use the get () method to visit the web page, and pass the parameters to the website we want to visit:

From selenium import webdriverbrowser = webdriver.Chrome () browser.get ('https://www.jd.com/')print(browser.page_source)

Through the above two lines of code, we can see that JD.com, who automatically opened the browser and visited it, printed JD.com 's source code on the console.

Of course, if you want the program to automatically close the browser, you can use:

Browser.close () 2.3 find a single node

After we get the web page, the first step is to find the DOM node first, and then we can get the data directly from the DOM node.

However, with Selenium, we can not only find nodes to obtain data, but also simulate user operations, such as entering something in the search box, clicking buttons, and so on, but let's first see how to find nodes:

As you can see from the picture above, if we want to get the input box, we can get it through id, so our next code is as follows:

From selenium import webdriverbrowser = webdriver.Chrome () browser.get ('https://www.jd.com/')input_key = browser.find_element_by_id (' key') print (input_key))

The results are as follows:

As you can see, the element type we got is WebElement.

Here is a list of all the ways to get a single node:

Find_element_by_idfind_element_by_namefind_element_by_xpathfind_element_by_link_textfind_element_by_partial_link_textfind_element_by_tag_namefind_element_by_class_namefind_element_by_css_selector

In addition, selenium has not yet provided a general method, find_element (), which requires passing in two parameters: the lookup method By and the value. In fact, the search method in the above example can also be written like this (the effect is exactly the same)

From selenium import webdriverfrom selenium.webdriver.common.by import Bybrowser = webdriver.Chrome () browser.get ('https://www.jd.com/')input_key1 = browser.find_element (By.ID,' key') print (input_key1) 2.4 find multiple nodes

For example, we need to find all the entries in this navigation bar on the left:

It can be written like this.

Lis = browser.find_elements_by_css_selector ('.cate _ menu li') print (lis)

The results are as follows:

[,

.]

All the multi-node selection methods are listed below:

Find_elements_by_namefind_elements_by_xpathfind_elements_by_link_textfind_elements_by_partial_link_textfind_elements_by_tag_namefind_elements_by_class_namefind_elements_by_css_selector

Similarly, there is a find_elements () method for multi-node selection.

3. wait for

Today, most Web applications use AJAX technology. When a browser loads a page, the elements in the page may be loaded at different intervals. This makes it difficult to locate the element: if the element does not already exist in the DOM, the locator function throws an ElementNotVisibleException exception. Using waiting, we can solve this problem. Waiting provides a certain amount of relaxation time between actions performed-mainly locating an element or any other operation on that element.

Selenium Webdriver provides two types of waits-implicit and explicit. Explicit wait causes WebDriver to wait for a specific condition to occur before continuing execution. Implicit waiting causes WebDriver to poll DOM for a certain amount of time when trying to find an element.

3.1 explicit wait

We can use time.sleep () to set the wait time, which is no problem at all, but it needs to set the condition to the exact period of time to wait. If we do not know the exact rendering time, we will not be able to set a more appropriate value.

Selenium provides us with WebDriverWait and ExpectedCondition to do this. Look at the code:

From selenium import webdriverfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected_conditions as ECdriver = webdriver.Chrome () driver.get ("https://www.jd.com/")try: element = WebDriverWait (driver, 10). Until (EC.presence_of_element_located ((By.ID," key ")) finally: driver.quit ()

The results are as follows:

Above, we use WebDriverWait to set the maximum waiting time. Here we choose to get the input box for the home page of JD. We limit the waiting time to 10s. If it cannot return a result within 10s, a TimeoutException will be thrown. By default, WebDriverWait calls ExpectedCondition every 500ms until it returns successfully.

3.2 implicit waiting

Implicit wait tells WebDriver to poll DOM for a certain amount of time when trying to find one or more elements that are not immediately available. The default setting is 0. Once set, implicit wait is set for the lifetime of the WebDriver object.

From selenium import webdriverdriver = webdriver.Chrome () driver.implicitly_wait # secondsdriver.get ("https://www.jd.com/")key = driver.find_element_by_id (" key ") print (key))

Node interaction

Selenium provides us with some interactive actions of nodes, such as the send_keys () method when typing text, the clear () method when emptying the text, and the click () method when clicking the button.

From selenium import webdriverimport timedriver = webdriver.Chrome () driver.implicitly_wait (10) driver.get ('https://www.taobao.com/')input = driver.find_element_by_id (' q') input.send_keys ('IPad') time.sleep (1) input.clear () input.send_keys (' Surface Pro') button = driver.find_element_by_class_name ('btn-search') button.click ()

In the above example, we first opened Taobao, and turned on implicit waiting, first entered IPad in the search box, deleted after waiting for 1 s, then entered Surface Pro, and then clicked the search button, first Taobao search requires users to log in to search, so we directly jumped to the login page.

Execute JavaScript

For some operations not provided by Selenium API, we can do this by simulating running JavaScript. The method used is execute_script (). For example, we slide the scroll bar to the bottom on the home page of Taobao:

From selenium import webdriverdriver = webdriver.Chrome () driver.get ('https://www.taobao.com/')driver.execute_script('window.scrollTo(0, document.body.scrollHeight)')

Get information

Earlier we showed how to get the DOM node, so the most important thing is that we need to get the information we need from the DOM node.

Because we are getting the WebElement type, and WebElement also provides relevant methods to extract node information.

From selenium import webdriverfrom selenium.webdriver.chrome.options import Options# instantiates a startup parameter object chrome_options = Options () # sets the browser window size chrome_options.add_argument ('--window-size=1366 768') # launch the browser driver = webdriver.Chrome (chrome_options=chrome_options) url = 'https://www.geekdigging.com/'driver.get(url)title = driver.find_element_by_xpath (' / / * [@ id= "text-4"] / div/div/div [1] / div [2] / a') print (title) # get attribute information print (title.get_attribute ('href')) # get text information print ( Title.text) # get location print (title.location) # get size print (title.size)

Above, because the default opening size of Chrome is a little small, the DOM node selected by the editor happens to be seen when opening the blog, so the editor sets the size when the Chrome browser is opened.

Specific information for your reference:

Parent: find the internal reference of the WebDriver instance of this element.

Rect: a dictionary with the size and location of elements.

Screenshot_as_base64: takes a screenshot of the current element in the form of an base64-encoded string.

Screenshot_as_png: takes a screenshot of the current element in binary data. The last two take a screenshot of the element, and it is easy to intercept the CAPTCHA when getting the CAPTCHA.

Forward and backward

We have a forward and back button at the top of the browser, and Selenium uses back () and forward () to complete these two actions.

Import timefrom selenium import webdriverbrowser = webdriver.Chrome () browser.get ('https://www.jd.com/')browser.get('https://www.taobao.com/')browser.get('https://www.geekdigging.com/')browser.back()time.sleep(1)browser.forward()

Cookies

It comes to another key content, Cookies, which is an important element of maintaining a conversation with the server. Selenium provides us with some methods, so that we can easily add, delete, modify and query Cookies. Examples are as follows:

From selenium import webdriverbrowser = webdriver.Chrome () browser.get ('https://www.geekdigging.com/')# get cookiesprint (browser.get_cookies ()) # add a cookiebrowser.add_cookie ({' name': 'name',' domain': 'www.geekdigging.com') 'value':' geekdigging'}) print (browser.get_cookies ()) # Delete all cookiebrowser.delete_all_cookies () print (browser.get_cookies ()) above is all the content of the article "how to use Selenium in python Automation testing" Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report