Playwright系列:第3章用Python、Nodejs、Java创建我们第一个脚本

2023-06-09 16:22:59 浏览数 (1)

我们基于Playwright实现以下步骤的自动化测试,用Python、Java和Nodejs实现,大家可以对比其中的异同。

‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍1. 启动Chromium浏览器 2. 访问example.com网站 3. 获取网页标题并打印 4. 点击"More information..."链接 5. 在搜索框输入"Playwright" 6. 等待2秒 7. 获取当前页面URL并打印 8. 关闭浏览器

Python示例:

代码语言:javascript复制
from playwright.sync_api import sync_playwright

def run(playwright):
    chromium = playwright.chromium
    browser = chromium.launch() # 启动Chromium浏览器
    page = browser.new_page() # 新建页面

# 访问示例网站
    page.goto("https://www.example.com/")  

# 获取页面标题
    title = page.title()
    print(title)

# 点击页面元素
    page.click("text=More information...")

# 输入文本
    page.fill("#search", "Playwright")

# 等待2秒
    page.wait_for_timeout(2000)  

# 获取当前URL
    url = page.url() 
    print(url)

# 关闭浏览器
    browser.close()

with sync_playwright() as playwright:
    run(playwright)

Node.js示例:

代码语言:javascript复制
const { chromium } = require('playwright');

(async () => {
const browser = await chromium.launch();
const page = await browser.newPage();

await page.goto('https://www.example.com/');
const title = await page.title();
console.log(title);

await page.click('text=More information...'); 
await page.fill('#search', 'Playwright');
await page.waitforTimeout(2000);

const url = await page.url();
console.log(url);

await browser.close();
})(); 

Java示例:

代码语言:javascript复制
import com.microsoft.playwright.*;

public class Example {
public static void main(String[] args) {
try (Playwright playwright = Playwright.create()) {
      BrowserType chromium = playwright.chromium();
      Browser browser = chromium.launch();
      Page page = browser.newPage();

      page.navigate("https://www.example.com/");
      String title = page.title();
      System.out.println(title);

      page.click("text=More information...");
      page.fill("#search", "Playwright");
      page.waitforTimeout(2000);

      String url = page.url();
      System.out.println(url);

      browser.close();
    }
  }
}

以上三个示例分别使用Python、Node.js和Java实现相同的测试逻辑。我们已经成功创建了第一个Playwright测试脚本,并实现了识别页面元素和简单操作。

接下来我们将继续学习Playwright更强大的页面操作功能,以编写出更丰富的测试脚本!

0 人点赞