11const puppeteer = require ( 'puppeteer' ) ;
22
33( async ( ) => {
4- // Launch the browser and open a new blank page
5- const browser = await puppeteer . launch ( ) ;
6- const page = await browser . newPage ( ) ;
4+ const browser = await puppeteer . launch ( {
5+ headless : true , // ← 顯示瀏覽器畫面
6+ slowMo : 100 // ← 每步操作加 100ms 延遲,方便觀察
7+ } ) ;
8+
79
8- // Navigate the page to a URL
9- await page . goto ( 'https://pptr.dev/' ) ;
10+ const page = await browser . newPage ( ) ;
11+ await page . goto ( 'https://pptr.dev/' ) ;
12+ await page . setViewport ( { width : 1280 , height : 800 } ) ;
1013
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
14+ await page . waitForSelector ( 'button.DocSearch-Button' ) ;
15+ await page . click ( 'button.DocSearch-Button' ) ;
1916
20- // Close the browser
21- await browser . close ( ) ;
22- } ) ( ) ;
17+ await page . waitForSelector ( 'input.DocSearch-Input' ) ;
18+ await page . type ( 'input.DocSearch-Input' , 'andy popoo' ) ;
19+
20+ const sections = await page . $$ ( 'section.DocSearch-Hits' ) ;
21+ let clicked = false ;
22+
23+ for ( const section of sections ) {
24+ // 抓出分類名稱
25+ const label = await section . $ ( '.DocSearch-Hit-source' ) ;
26+ const labelText = label
27+ ? await label . evaluate ( el => el . textContent . trim ( ) )
28+ : '' ;
29+
30+ // 如果是 Documentation 區塊
31+ if ( labelText === 'ElementHandle' ) {
32+ const firstLink = await section . $ ( 'li.DocSearch-Hit a' ) ;
33+ if ( firstLink ) {
34+ await firstLink . click ( ) ;
35+
36+ // 給點時間等待跳轉或內容更新(因為可能是錨點 #)
37+ await new Promise ( resolve => setTimeout ( resolve , 1000 ) ) ;
38+
39+ const title = await page . $eval ( 'h1' , el => el . textContent . trim ( ) ) ;
40+ console . log ( title ) ;
41+
42+
43+ clicked = true ;
44+ break ;
45+ } else {
46+ console . warn ( "⚠️ Documentation 區有資料,但沒有可點擊連結" ) ;
47+ }
48+ }
49+ }
50+ await browser . close ( ) ;
51+ } ) ( ) ;
0 commit comments