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 install the Selenium framework in Python

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

Share

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

This article focuses on "how to install the Selenium framework in Python". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to install the Selenium framework in Python.

Selenium is a framework for testing Web applications, which runs directly in the browser, just like real user actions. It supports multiple platforms: Windows, Linux, Mac, multiple languages: Python, Perl, PHP, C #, etc., and supports multiple browsers: Chrome, IE, Firefox, Safari and so on.

1 installation

1) install Selenium

Pip install selenium

2) install WebDriver

The main browser WebDriver address is as follows:

Chrome: http://chromedriver.storage.googleapis.com/index.html

Firefox: https://github.com/mozilla/geckodriver/releases/

IE: http://selenium-release.storage.googleapis.com/index.html

This article takes Chrome as an example, this machine is a Windows system, WebDriver uses version 78.0.3904.11 Chrome browser version 78.0.3880.4, download and decompress the driver, and put chromedriver.exe in the Python installation directory.

2 operating browser

2.1 Open the browser

1) normal mode

Take opening to 163mailbox as an example, use Chrome browser

From selenium import webdriver

Browser = webdriver.Chrome ()

Browser.get ('https://mail.163.com/')

Use the Firefox browser

From selenium import webdriver

Browser = webdriver.Firefox ()

Browser.get ('https://mail.163.com/')

Use the IE browser

From selenium import webdriver

Browser = webdriver.Ie ()

Browser.get ('https://mail.163.com/')

2) load configuration mode

Take Chrome as an example, enter chrome://version/ in the address bar of the Chrome browser to open it, as shown in the figure:

We can see the profile path, get the path: C:\ Users\ admin\ AppData\ Local\ Google\ Chrome\ User Data, get the configuration set by User Data, and get Default to use the default configuration. Look at the following example:

From selenium import webdriver

Option = webdriver.ChromeOptions ()

# your own data directory (need to replace\ in the copied path with / or escape\)

# option.add_argument ('--user-data-dir=C:/Users/admin/AppData/Local/Google/Chrome/User Data')

Option.add_argument ('- user-data-dir=C:\\ Users\\ admin\\ AppData\\ Local\\ Google\\ Chrome\\ User Data')

Browser = webdriver.Chrome (chrome_options=option)

Browser.get ('https://mail.163.com/')

# close

Browser.quit ()

If the execution Times fails to open the specified page, you can close the browser before executing.

3) Headless mode

The first two ways are the way of browser interface, Headless mode is the interface-free form of Chrome browser, you can use all the features supported by Chrome to run our program without opening the browser. This method is more convenient to test Web applications, get screenshots of websites, and do crawlers to capture information. Look at the following example:

From selenium import webdriver

Chrome_options = webdriver.ChromeOptions ()

# using headless UI-less browser mode

Chrome_options.add_argument ('--headless')

# disable gpu acceleration

Chrome_options.add_argument ('--disable-gpu')

# launch the browser to get the source code of the web page

Browser = webdriver.Chrome (chrome_options=chrome_options)

Url = 'https://mail.163.com/'

Browser.get (url)

Print ('browser text =', browser.page_source)

Browser.quit ()

2.2 set up the browser window

Maximize display

Browser.maximize_window ()

Minimize display

Browser.minimize_window ()

Custom Siz

# 500 wide, 800 high

Browser.set_window_size (500800)

2.3 forward and backward

Forward

Browser.forward ()

Step back

Browser.back ()

3 element positioning

When we want to manipulate an element, we first need to find it. Selenium provides a variety of ways to locate elements. Let's take the Chrome browser Headless as an example. Look at the following example:

From selenium import webdriver

Chrome_options = webdriver.ChromeOptions ()

Chrome_options.add_argument ('--headless')

Chrome_options.add_argument ('--disable-gpu')

Browser = webdriver.Chrome (chrome_options=chrome_options)

Url = 'https://xxx.xxx.com/'

Browser.get (url)

Data = browser.page_source

Assuming the access address https://xxx.xxx.com/, the returned data is as follows.

Index

1) locate according to id

Browser.find_element_by_id ('fid')

2) locate according to name

# return the first element

Browser.find_element_by_name ('fname')

# return all elements

Browser.find_elements_by_name ('fname')

3) locate according to class

# return the first element

Browser.find_element_by_class_name ('fname')

# return all elements

Browser.find_elements_by_class_name ('fname')

4) locate according to the label signature

# return the first element

Browser.find_element_by_tag_name ('input')

# return all elements

Browser.find_elements_by_tag_name ('input')

5) use CSS to locate

# return the first element

Browser.find_element_by_css_selector ('.fname')

# return all elements

Browser.find_elements_by_css_selector ('.fname')

6) use link text to locate hyperlinks

# return the first element

Browser.find_element_by_link_text ('index')

# return all elements

Browser.find_elements_by_link_text ('index')

# return the first element

Browser.find_element_by_partial_link_text ('index')

# return all elements

Browser.find_elements_by_partial_link_text ('index')

7) use xpath to locate

# return the first element

Browser.find_elements_by_xpath ("/ / input [@ id='fid']")

# return all elements

Browser.find_elements_by_xpath ("/ / input [@ name='fname']")

4 wait for event

Most Web applications use AJAX technology to load. When a browser loads a page, the elements in the page may be loaded at different times, which makes it more difficult to locate the elements, because the elements are not in the DOM and will throw an ElementNotVisibleException exception. Using Waits, we can solve this problem. How much does it cost to be a man in Wuxi, http://mobile.ytsg029.com/?

Selenium WebDriver provides both explicit and implicit Waits modes. Explicit Waits causes WebDriver to wait for a certain condition to trigger before further execution, while implicit Waits allows WebDriver to poll DOM a specified number of times when trying to locate an element.

4.1 display wait

With the until () and until_not () methods of this class, WebDriverWait can wait flexibly according to the judgment conditions. Its main process is: the program checks every x seconds, if the condition is set, then perform the next step, otherwise continue to wait until the maximum set time is exceeded, and then throw a TimeoutException exception. Take a look at the method first:

_ _ init__ (driver, timeout, poll_frequency=POLL_FREQUENCY, ignored_exceptions=None)

Driver: pass in WebDriver instance

Timeout: timeout (in seconds)

Poll_frequency: the interval between calls to methods in until or until_not. The default is 0.5 seconds.

Ignored_exceptions: ignored exception. If an exception in this tuple is thrown during the call to until or until_not, the code will continue to wait without interrupting the code. If an exception outside this tuple is thrown, the code will be interrupted and an exception will be thrown. Only NoSuchElementException is the default.

Until (method, message='')

Method: this method is called at regular intervals (poll_frequency in init) while waiting until the return value is not False

Message: if the timeout occurs, TimeoutException is thrown and message is passed into the exception.

Until_not (method, message='')

The until method continues to execute when a certain condition is true, while the until_not method is on the contrary, it continues to execute when a certain condition is not true, and the parameters are the same as the until method.

Take going to mailbox 163 as an example, take a look at the example:

From selenium import webdriver

From selenium.webdriver.common.by import By

From selenium.webdriver.support.ui import WebDriverWait

From selenium.webdriver.support import expected_conditions as EC

Browser = webdriver.Chrome ()

Browser.get ('https://mail.163.com/')

Try:

# the timeout is 5 seconds

Data = WebDriverWait (browser,5). Until (

EC.presence_of_element_located ((By.ID,'lbNormal'))

)

Print (data)

Finally:

Browser.quit ()

In the example, the code waits for 5 seconds, and if an element is found within 5 seconds, it will be returned immediately, otherwise a TimeoutException exception will be thrown. WebDriverWait defaults to calling ExpectedCondition every 0.5 seconds until it returns successfully.

4.2 implicit waiting

When we are looking for an element or elements that are not immediately available, the implicit Waits tells WebDriver to poll DOM for the specified number of times. The default setting is 0. Once set, the implicit call for the entire life cycle of the WebDriver object instance is set. Take a look at the method:

Implicitly_wait (time_to_wait)

Implicit wait is to set a maximum wait time time_to_wait, if the page loads within the specified time, then execute the next step, otherwise wait until the time expires, and then perform the next step. When we see this, we feel a bit like time.sleep (). The difference is that time.sleep () must wait for a specified time before it can continue to execute, time_to_wait is executed after loading in the specified time range, and time_to_wait is more flexible than time.sleep ().

Look at the following example:

From selenium import webdriver

Browser = webdriver.Chrome ()

Browser.implicitly_wait (5)

Browser.get ('https://mail.163.com/')

Data = browser.find_element_by_id ('lbNormal')

Print (data)

Browser.quit ()

5 Log in to 163 mailbox

Finally, we use Selenium to do a practical example of logging in to 163mailbox.

5.1 Mode 1

We log in at the address https://email2.163.com/, as shown in the figure:

From the picture, we found that directly into the 163 email user name, password login page, we directly enter the user name, password, click the login button. Examples are as follows:

From selenium import webdriver

Browser = webdriver.Chrome ()

Browser.get ('https://email2.163.com/')

Browser.switch_to.frame (browser.find_element_by_xpath ('/ / iframe [starts-with (@ id, "x-URS")]')

Browser.implicitly_wait (2)

# your own user name

Browser.find_element_by_xpath ('/ / input [@ name= "email"]') .send_keys ('xxx')

# your own password

Browser.find_element_by_xpath ('/ / input [@ name= "password"]') .send_keys ('xxx')

Browser.find_element_by_xpath ('/ / * [@ id= "dologin"]') .click ()

Browser.implicitly_wait (2)

Print (browser.page_source)

Browser.implicitly_wait (2)

# close

Browser.quit ()

At this point, I believe you have a deeper understanding of "how to install the Selenium framework in Python". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

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