- 访问百度首页
import { test, expect } from '@playwright/test';
test.describe('baiduTopPage', () => {
test.beforeEach('open baiduToppage', async ({ page }) => {
await page.goto('https://www.baidu.com/');
});
test('Open a page and assert title', async ({ page }) => {
const pageTitle = await page.title();
console.log(pageTitle);
expect(pageTitle).toContain('百度一下,你就知道');
});
})
- 比较图片
import { test, expect } from '@playwright/test';
import * as fs from 'fs';
test('image compare', async ({ page }) => {
let hasImage = false
page.on('response', async response => {
if(response.url().includes('PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png')) {
hasImage = true
const response_buffer = await response.body()
const local_image = await readFileAsync('downloaded_baiduPic.png')
expect(response_buffer.toString('utf-8')).toEqual(local_image)
}
});
await page.goto('https://www.baidu.com/');
if (!hasImage){
throw new Error('not found picture!');
}
});
function readFileAsync(filePath: string): Promise<string> {
return new Promise((resolve, reject) => {
// 读取本地文件
fs.readFile(filePath, 'utf-8', (err, data) => {
if (err) {
reject(err);
} else {
resolve(data);
}
});
});
}
- 下载图片
import { test, expect } from '@playwright/test';
import * as fs from 'fs';
test('image download', async ({ page }) => {
let hasImage = false;
page.on('response', async response => {
if (response.url().includes('PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png')){
const response_buffer = await response.body()
hasImage = true;
await writeFileAsync('download_baiduPic.png',response_buffer)
}
});
await page.goto('https://www.baidu.com/');
// expect(hasImage).toEqual(true)
if (!hasImage){
throw new Error('not found picture!');
}
});
function writeFileAsync(filePath, data) {
return new Promise<void>((resolve, reject) => {
fs.writeFile(filePath, data, 'utf-8', (err) => {
if (err) {
console.error('图片读取发生错误!:', err);
reject(err);
} else {
console.log('图片已下载');
resolve();
}
});
});
}
比较豆瓣“消费降级”小组人数大于35万
import { test, expect } from '@playwright/test';
test('比较 消费降级小组的成员人数是否大于35万', async ({ page }) => {
await page.goto('https://www.douban.com/group/644670/');
//定位到包含小组人数的元素
const numLocator = await page.locator('//*[@id="content"]/div[2]/div[2]/div[3]/p/a');
//获取元素的innerText()
const numStr = await numLocator.innerText()
// <a href="https://www.douban.com/group/644670/members">浏览所有骄傲的倔降 (359495)</a>
// 用正则提取数字
const regex = /\((\d+)\)/; // 匹配括号内的数字
const match = numStr.match(regex);
if (match && match[1]) {
const numberStr = match[1];
console.log(`提取的数字是:${numberStr}`);
//数字现在是str类型,需要转成int
const numberInt = Number(numberStr);
// 对比数字是否大于35w
expect(numberInt).toBeGreaterThan(350000);
} else {
console.log('未找到匹配的数字');
}
});