Skip to content

[LAB4] 313551149 #341

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: 313551149
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 65 additions & 1 deletion lab4/main_test.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,71 @@ const puppeteer = require('puppeteer');

// Navigate the page to a URL
await page.goto('https://pptr.dev/');
// Click search button
await page.click('.DocSearch');

// Wait for search modal to appear
await page.waitForSelector('.DocSearch-Modal');

// Type into search box
await page.waitForSelector('.DocSearch-Input');
await page.type('.DocSearch-Input', 'andy popoo');

// Wait for search results to appear
await page.waitForSelector('.DocSearch-Hit-source');

// 增加等待時間,確保所有結果都完全加載
await new Promise(resolve => setTimeout(resolve, 1000));

// 使用page.evaluate直接在頁面上下文中找到ElementHandle部分並點擊第一個結果
const clicked = await page.evaluate(() => {

const sections = document.querySelectorAll('.DocSearch-Hit-source');


// 尋找包含ElementHandle的部分
for (let i = 0; i < sections.length; i++) {
if (sections[i].textContent.includes('ElementHandle')) {

// 獲取這個部分的父元素
const sectionParent = sections[i].parentElement;

// 找到緊跟在這個部分後的第一個ul元素(這個ul包含搜索結果)
let nextElement = sections[i].nextElementSibling;
while (nextElement && nextElement.tagName !== 'UL') {
nextElement = nextElement.nextElementSibling;
}

if (nextElement && nextElement.tagName === 'UL') {
// 找到ul中的第一個li元素(第一個搜索結果)
const firstLi = nextElement.querySelector('li');

if (firstLi) {
// 找到這個li中的a元素
const link = firstLi.querySelector('a');

if (link) {

link.click();
return true;
}
}
}

break;
}
}

return false;
});


// Wait for page to load
await page.waitForSelector('h1');

// Get the title text
const title = await page.$eval('h1', el => el.textContent);
console.log(title);
// Hints:
// Click search button
// Type into search box
Expand All @@ -19,4 +83,4 @@ const puppeteer = require('puppeteer');

// Close the browser
await browser.close();
})();
})();
Loading