1
1
const puppeteer = require ( 'puppeteer' ) ;
2
2
3
+ // 等待函式
4
+ function wait ( ms ) {
5
+ return new Promise ( resolve => setTimeout ( resolve , ms ) ) ;
6
+ }
7
+
3
8
( 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 可觀察流覽器操作
6
11
const page = await browser . newPage ( ) ;
7
12
8
- // Navigate the page to a URL
13
+ // 導航到指定URL
9
14
await page . goto ( 'https://pptr.dev/' ) ;
10
15
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