啟動瀏覽器
- 開啟瀏覽器介面:headless: false
- 開啟開發者控制檯:devtools: true
- 自定義瀏覽器寬高:page.setViewport
- 產生兩個tab頁
- 官方開啟頁面:await browser.pages(),會產生兩個tab頁,一個是目標tab頁,一個是blank頁
- 修改後:(await browser.pages())[0],僅開啟目標tab頁
async init() {
await this.openPage();
await this.createCer();
}
async openPage() {
browser = await puppeteer.launch({
headless: false,
devtools: true,
});
page = (await browser.pages())[0];
try {
await page.setViewport({
width: 1300,
height: 938,
});
await page.goto("http://127.0.0.1/demo.html");
} catch (error) {
await this.openPage();
throw new Error(`請求頁面超時,嘗試重新連線`);
}
}
複製程式碼
操作頁面
- 為了能夠獲取目標節點,當遇到頁面跳轉的時、點選下拉時、可先等待隨機秒數:await page.waitFor(utilFun.random(1000, 3000));
- 想獲取元素的屬性:page.$eval()
- 想操作dom元素:page.evaluate()
- 為了能夠準確獲取dom元素,可使用setTimeout延時諾幹秒後,再進行相應操作
- 正則中若想含有變數: let reg = new RegExp(
${username}
);
async createCer() {
const type = this.type;
const Development = "#ios-nav > li:nth-child(1) ul > li:nth-child(3)";
const Production = await page.$("#ios-nav > li:nth-child(1) ul > li:nth-child(4)");
switch (type) {
case "dev":
await this.addIosCertificates(Development);
break;
case "dis":
await this.addIosCertificates(Production);
break;
default:
break
}
}
async addIosCertificates(ele) {
await page.waitFor(utilFun.random(1000, 3000));
await page.click(ele);
await page.waitFor(utilFun.random(1000, 3000));
await page.click(".toolbar-button.add");
await page.waitFor(utilFun.random(1000, 3000));
const radioDisabled = await page.$eval("#type-development-0", async el => {
return el.disabled;
});
if (radioDisabled) {
await page.waitFor(utilFun.random(1000, 3000));
await page.click(`${ele}`);
await page.waitFor(utilFun.random(1000, 3000));
await this.deleteCer();
} else {
await this.addCer();
}
}
async deleteCer() {
await page.evaluate(async (username) => {
let tableInfo = "";
let reg = new RegExp(`${username}`);
const table = document.querySelectorAll(".data-table")[1].querySelector("tbody");
for (let i = 0; i < table.rows.length; i++) {
for (let j = 0; j < table.rows[i].cells.length; j++) {
tableInfo = table.rows[i].cells[j].innerText;
if (reg.test(tableInfo) && (i % 2 == 0)) {
let name = table.rows[i].cells[j].innerText;
let type = table.rows[i].cells[j + 1].innerText;
let expires = table.rows[i].cells[j + 2].innerText;
table.rows[i].click();
setTimeout(() => {
document.querySelector(".button-no-padding-top.small.revoke-button").click();
}, 1000);
setTimeout(() => {
document.querySelector(".ui-dialog-content.ui-widget-content .button.small.red.ok").click();
}, 3000);
}
}
}
}, username);
}
複製程式碼
上傳檔案
await page.waitFor(utilFun.random(1000, 3000));
const upload_file = await page.$("input[type=file]");
await upload_file.uploadFile("你的檔案路徑");
複製程式碼
檔案下載
await this.downloadFile("你的檔案路徑");
await page.waitFor(utilFun.random(1000, 3000));
await page.click(".button.small.blue");
複製程式碼