程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Microsofts open source Python automation artifact playwright, without writing a line of code

編輯:Python

Hello everyone , I'm little brother .

I believe that friends who have played with reptiles all know selenium, A artifact tool for automated testing . Write a Python Automated scripts are basically routine operations , Reptiles can't climb , Just use automated testing to make up for it .

although selenium There are complete documentation , But it also requires a certain learning cost , For a pure white, there are still some threshold .

lately , Microsoft open source a project called 「playwright-python」, It's a blockhouse ! This project is aimed at Python The pure automation tool of language , You don't have to write code , We can realize the automation function .

Maybe you think it's a little weird , But it's just that powerful . Let's take a look at this artifact .

1. Playwright Introduce

Playwright Is a powerful Python library , Use only one API It can be executed automatically ChromiumFirefoxWebKit And other mainstream browser automation operations , And support headless mode at the same time 、 Head mode operation .

Playwright The automation technology provided is green 、 Powerful 、 Reliable and fast , Support LinuxMac as well as Windows operating system .

2. Playwright Use

install

Playwright The installation of is very simple , Two steps .

# install playwright library
pip install playwright
# Install browser driver files ( The installation process is a little slow )
python -m playwright install
Copy code 

The top two pip The operation is installed separately :

  • install Playwright Dependency Library , need Python3.7+

  • install Chromium、Firefox、WebKit Wait for the browser's driver file

Recording

Use Playwright No need to write a line of code , We just need to manually operate the browser , It will record our actions , And then automatically generate code scripts .

Here's the recording command codegen, Just one line .

# Type... On the command line --help You can see all the options
python -m playwright codegen
Copy code 

codegen You can use --help see , If it is simple to use, it is to add url link , If you have other needs, you can add options.

python -m playwright codegen --help
Usage: index codegen [options] [url]
open page and generate code for user actions
Options:
-o, --output <file name> saves the generated script to a file
--target <language> language to use, one of javascript, python, python-async, csharp (default: "python")
-h, --help display help for command
Examples:
$ codegen
$ codegen --target=python
$ -b webkit codegen https://example.com
Copy code 

options meaning :

  • -o: Save the recorded script to a file

  • --target: Specify the language in which the script is generated , Yes JS and Python Two kinds of , The default is Python

  • -b: Specify browser driver

such as , I want to be in baidu.com Search for , use chromium drive , Save results as my.py Of python file .

python -m playwright codegen --target python -o 'my.py' -b chromium https://www.baidu.com
Copy code 

After the command line input, the browser will be opened automatically , Then you can see that every move on the browser is automatically translated into code , As shown below .

Automatically close the browser when finished , Save the generated automation script to py file .

from playwright import sync_playwright
def run(playwright):
browser = playwright.chromium.launch(headless=False)
context = browser.newContext()
# Open new page
page = context.newPage()
page.goto("https://www.baidu.com/")
page.click("input[name=\"wd\"]")
page.fill("input[name=\"wd\"]", "jingdong")
page.click("text=\" JD.COM \"")
# Click //a[normalize-space(.)=' JD.COM JD.COM Official website Achieve greater, faster, better and more economical results Just for quality life ']
with page.expect_navigation():
with page.expect_popup() as popup_info:
page.click("//a[normalize-space(.)=' JD.COM JD.COM Official website Achieve greater, faster, better and more economical results Just for quality life ']")
page1 = popup_info.value
# ---------------------
context.close()
browser.close()
with sync_playwright() as playwright:
run(playwright)
Copy code 

Besides ,playwright It also provides both synchronous and asynchronous API Interface

Sync

The following example code : Open three browsers in turn , Go to baidu Search for , 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]:
browser = browser_type.launch()
page = browser.newPage()
page.goto('https://baidu.com/')
page.screenshot(path=f'example-{browser_type.name}.png')
browser.close()
Copy code 

asynchronous

Asynchronous operations can be combined with asyncio Three browser operations at the same time .

import asyncio
from playwright import async_playwright
async 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('http://baidu.com/')
await page.screenshot(path=f'example-{browser_type.name}.png')
await browser.close()
asyncio.get_event_loop().run_until_complete(main())
Copy code 

Mobile

Even worse ,playwright It can also support mobile browser emulation . The following is a code provided by the official document , Simulate a mobile phone in a given geographic location iphone 11 pro Upper Safari browser , First navigate to maps.google.com, Then perform positioning and take a screenshot .

from playwright import sync_playwright
with sync_playwright() as p:
iphone_11 = p.devices['iPhone 11 Pro']
browser = p.webkit.launch(headless=False)
context = browser.newContext(
**iphone_11,
locale='en-US',
geolocation={ 'longitude': 12.492507, 'latitude': 41.889938 },
permissions=['geolocation']
)
page = context.newPage()
page.goto('https://maps.google.com')
page.click('text="Your location"')
page.screenshot(path='colosseum-iphone.png')
browser.close()
Copy code 

in addition , It can also cooperate with pytest Plug in to work with , If you are interested, you can try it yourself .

3. summary

playwright Compared with the existing automated testing tools, it has many advantages , such as :

  • Cross browser , Support Chromium、Firefox、WebKit
  • Cross operating system , Support Linux、Mac、Windows
  • It can record and generate code , Liberating hands
  • It can be used in mobile terminals

The drawback is that the ecology and documentation are not very complete , Such as no API Chinese document 、 There are no good tutorials and examples to learn . But believe , As more and more people know , The future will be better and better .


Software testing learning resource sharing

Finally, thank everyone who reads my article carefully , Watching the rise and attention of fans all the way , Reciprocity is always necessary , Although it's not very valuable , If you can use it, you can take it

These materials , For doing 【 software test 】 For our friends, it should be the most comprehensive and complete war preparation warehouse , This warehouse also accompanied me through the most difficult journey , I hope it can help you ! Everything should be done as soon as possible , Especially in the technology industry , We must improve our technical skills . I hope that's helpful ……


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved