Skip to content

Commit 7423d27

Browse files
authored
Merge pull request #415 from Yyrff/lab4
[LAB4] 511558014
2 parents 4b54fde + b764bcc commit 7423d27

File tree

1 file changed

+48
-15
lines changed

1 file changed

+48
-15
lines changed

lab4/main_test.js

Lines changed: 48 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,55 @@
11
const puppeteer = require('puppeteer');
22

3+
// 等待函式
4+
function wait(ms) {
5+
return new Promise(resolve => setTimeout(resolve, ms));
6+
}
7+
38
(async () => {
4-
// Launch the browser and open a new blank page
5-
const browser = await puppeteer.launch();
9+
// 啟動流覽器並打開新頁面
10+
const browser = await puppeteer.launch({ headless: true }); // headless: false 可觀察流覽器操作
611
const page = await browser.newPage();
712

8-
// Navigate the page to a URL
13+
// 導航到指定URL
914
await page.goto('https://pptr.dev/');
1015

11-
// Hints:
12-
// Click search button
13-
// Type into search box
14-
// Wait for search result
15-
// Get the `Docs` result section
16-
// Click on first result in `Docs` section
17-
// Locate the title
18-
// Print the title
19-
20-
// Close the browser
21-
await browser.close();
22-
})();
16+
try {
17+
// 等待並點擊搜索按鈕
18+
await wait(1000);
19+
const searchButtonSelector = "#__docusaurus > nav > div.navbar__inner > div.navbar__items.navbar__items--right > div.navbarSearchContainer_Bca1 > button > span.DocSearch-Button-Container > span";
20+
21+
await page.click(searchButtonSelector);
22+
23+
// 等待搜索輸入框出現並輸入搜索關鍵字
24+
await wait(1000);
25+
const searchInputSelector = '#docsearch-input';
26+
await page.type(searchInputSelector, 'chipi chipi chapa chapa');
27+
28+
// 等待
29+
await wait(1000);
30+
// await page.waitForSelector('#docsearch-item-5 > a'); // 等待搜索結果的特定項出現
31+
32+
// 點擊搜索結果中的特定項
33+
await page.click('#docsearch-item-5 > a');
34+
35+
// 等待頁面載入完成
36+
// await page.waitForNavigation({ waitUntil: 'networkidle0' });
37+
38+
// 使用 page.evaluate 獲取元素的文本內容
39+
await wait(1000);
40+
const titleText = await page.evaluate(() => {
41+
const titleElement = document.querySelector('h1');
42+
return titleElement ? titleElement.innerText : '';
43+
});
44+
45+
// 列印標題文本
46+
console.log(titleText);
47+
48+
} catch (error) {
49+
// 捕捉到任何錯誤並輸出
50+
console.error('發生bug:', error);
51+
} finally {
52+
// 確保流覽器關閉
53+
await browser.close();
54+
}
55+
})();

0 commit comments

Comments
 (0)