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 Playwright

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

Share

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

This article mainly explains "how to use Playwright". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn how to use Playwright.

Playwright is a new generation of automated testing tool released by Microsoft at the beginning of 2020. Compared with the most commonly used Selenium, it can automatically execute mainstream browser automation operations such as Chromium, Firefox, WebKit and so on with only one API. As a tool for pure automation of Python language, it can be automated more quickly in regression testing.

1. Why choose Playwright?

1.1 benefits of Playwright

(1) Selenium needs to operate the browser through WebDriver; Playwright interacts with the browser through developer tools, the installation is simple, and there is no need to install all kinds of Driver.

(2) Playwright supports almost all languages and does not depend on all kinds of Driver, so it starts faster by calling the built-in browser.

(3) Selenium is based on HTTP protocol (one-way communication), and Playwright based on Websocket (two-way communication) can automatically obtain the actual situation of the browser.

(4) Playwright is automatic waiting.

Wait for the element to appear (automatically wait for 30s when positioning the element, and the waiting time can be customized in milliseconds)

Waiting for the event to happen.

1.2 known limitations

(1) Playwright does not support older versions of Microsoft Edge or IE11. Support for the new Microsoft Edge (on Chromium); so projects that have rigid requirements for browser versions are not applicable.

(2) websites that need SSL certificates to visit may not be able to record, and the process needs to be written separately.

(3) the mobile test simulates the mobile device through the desktop browser (equivalent to having its own simulator), and cannot control the real machine.

2. Playwright usage

2.1 installation

(1) install Playwright dependent libraries (Playwright supports Async\ Await syntax, so Python3.7+ is required)

Pip install playwright

(2) install the driver files of Chromium, Firefox, WebKit and other browsers (built-in browser)

Python-m playwright install2.2 automatic recording

(1) Command line type-- help sees all the options that can be followed by

Python-m playwright codegen-- help

(2) start recording for xingzheai.cn from the start page

Python-m playwright codegen https://xingzheai.cn/

(3) Open xingzheai.cn, use Chromium driver, and save the result to the python file of my.py.

Python-m playwright codegen-- target python-o 'my.py'-b chromium https://xingzheai.cn/

-target: specifies the language in which scripts are generated. There are JS and Python. The default is Python.

-b: specify browser driver

-o: save the recorded script to a file

2.3 customized compilation

(1) element positioning

Select a single element: querySelector (engine=body)

Select multiple elements: querySelectorAll (engine=body)

Select a single element and automatically wait: waitForSelector (engine=body)

There are 8 kinds of positioning methods of By, and there are actually 4 kinds of positioning methods.

Id, name, tag name, class name (java and pythona classify all four as CSS)

Xpath 、 link text 、 partial link text 、 css selector

The webDriver protocol specified in the W3C standard has five positioning modes.

CSS 、 Link text 、 Partial link text 、 Tag name 、 XPath

Playwright sums up the selector into three

CSS, XPATH (support for logical expressions and functions), TEXT

(2) Selector rule

CSS: ID selector, class selector, element selector, attribute selector, wildcard selector, hierarchical selector.

XPath: XML path language, through the "path identifier", navigation XML documents, in the class XML (HTML) can also be used.

Text: structured content (html,xml,json) uses fuzzy matching (ignore case, ignore spaces before and after, search for substrings) and exact matching, while unstructured content uses regular matching.

(3) Common operation of elements

Drop-down selection box: selectOpion, value, labei, index

File upload: setInputFiles, single file, multiple files, drag and drop upload

Mouse click: click, dbclick

Mouse drag: down, up

Mouse movement: move

Touch screen: tag

Keyboard keys: press

Screenshot and screenshot: screenshot, recordVideo

2.4 Network interception (Mock API). Examples are as follows:

Page = context.newPage () def Whether_intercept ()-> bool: return True # intercept # return False # do not intercept def handler (route:Route): print (route.request.url) # normal access # route.continue_ () # access denied # route.abort ("network blocking") # redirect to non-destination address route.fulfill (status=302 Headers= {'Location': "https://xingzheai.cn/"}) page.route (Whether_intercept,handler)

2.5 synchronous execution. Examples are as follows:

# Open three browsers in turn, go to the traveler's official website, take a screenshot and exit. From playwright import sync_playwright with sync_playwright () as p: for browser_type in [p.chromium, p.firefox, p.webkit]: # specified as header mode Ture is headless mode browser = browser_type.launch (headless=False) page = browser.newPage () page.goto ('https://xingzheai.cn/') # wait for the page to load completely after screenshot page.waitForSelector ("text= Smart content Review") page.screenshot (path=f'example- {browser_type.name} .p ng') browser.close () 2.6 is executed asynchronously, as shown below:

# simultaneously perform three browser operations import asynciofrom playwright import async_playwrightasync def main (): async with async_playwright () as p: for browser_type in [p.chromium, p.firefox P.webkit]: browser = await browser_type.launch () page = await browser.newPage () await page.goto ('https://xingzheai.cn/') await page.waitForSelector ("text= Smart content Review") await page.screenshot (path=f'example- {browser_type.name} .png') await browser.close () asyncio.get_event_loop ( ). Run_until_complete (main ()) 2.7 Pytest binding Examples are as follows:

Installation: pip install pytest-playwright

Def test_playwright (page): page.goto ("https://xingzheai.cn/") with page.expect_popup () as popup_info: page.click ('text=" Smart content Audit ") assert" Smart content Audit "= = element.textContent () 2.8Mobile operation. Examples are as follows:

At present, there are few simulation models. Refer to: simulation equipment list.

From time import sleepfrom playwright import sync_playwright with sync_playwright () as p: GalaxyS5 = p.devices ['GalaxyS5'] browser = p.chromium.launch (headless=False) context = browser.newContext (* * GalaxyS5) page = context.newPage () page.goto ('https://xingzheai.cn/') page.click (' text= "Smart content Review") # Screenshot # page.screenshot (path='colosseum-GalaxyS5.png' ) sleep (10) browser.close () Thank you for your reading The above is the content of "how to use Playwright". After the study of this article, I believe you have a deeper understanding of how to use Playwright, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

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