我的GitHub
0%

无星的自动化之旅(六)——PlayWright封装的代码块合集

封装的代码块合集

浏览器的创建

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
const { chromium } = require('playwright');
const authState = require('../auth/auth.json');
const { getOS } = require('../utils/utils');
// 初始化一个页面
const createBrower = async () => {
const os = getOS()
// 判断系统类型使用不同参数
let params = {}
if (os === 'Windows_NT') {
params = {
headless: false,
// 使用edge浏览器
channel: 'msedge',
args: [
"--start-maximized",
"--disable-web-security",
"--allow-running-insecure-content"
]
}
} else {
params = {
headless: false,
// 使用其他浏览器
executablePath: "/usr/bin/browser360ent-cn",
args: [
"--start-maximized",
"--disable-web-security",
"--allow-running-insecure-content"
]
}
}
const browser = await chromium.launch(params);
const context = await browser.newContext({
// 全屏填null
viewport: null,
storageState: authState,
// 忽略https的问题
ignoreHTTPSErrors: true
});
const page = await context.newPage({
});

return {
browser,
context,
page
}
}

module.exports = {
createBrower,
}

TODO: 手动开启浏览器,链接到已有浏览器

拦截网络请求并替换结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const forbidRequest = async (page) => {
// 参数可以填请求地址或者正则表达式,例如:/aaa$/以aaa开头的请求
page.route('参数', async route => {
// Fetch original response.
const response = await page.request.fetch(route.request());
// Add a prefix to the title.
let body = {}
// 这里要注意,一定要转json字符串
const result = JSON.stringify(body)
route.fulfill({
// Pass all fields from the response.
response,
// Override response body.
body:result,
});
});
}

网页输入框无法输入

本来对于输入框,应该使用page.fill()去输入

但是总有一些奇奇怪怪的情况,无法输入

对于这种情况,我们可以通过page.key去操作键盘输入

例如我要输入账号密码

1
2
3
4
5
6
7
8
9
10
11
const account = ''
const password = ''

await page.keyboard.insertText(account);
await page.keyboard.press('Tab');

const pArray = password.split('');
for(let index = 0; index < pArray.length; index ++){
const element = pArray(index)
await page.keyboard.down(element);
}
我是阿星,阿星的阿,阿星的星!