2017-10-04 59 views
0

閱讀文檔和示例後,我仍然有理解如何通過ElementHandle響應page.$$導航的問題。

大多數希望使用page.$$和隱含地使用document.querySelectorAll()的用例都是獲取數組或NodeList,然後在其上工作。

比方說,我們有一個包含5個鏈接的頁面,我想在腳本中打印第二個a的href。這是我試過的,它不起作用。

const linksArray = await page.$$('a'); 
const the2ndHref = await page.evaluate(linkList => linkList[1].href, linksArray); 
console.log('the2ndHref', the2ndHref); 
await linksArray.dispose(); 

你能幫忙嗎?

回答

1

我的猜測是,你不真正想要的ElementHandle因爲ElementHandle表示DOM元素,您可以與properties驅動像clickfocushover

如果你想獲得的鏈接中的href,你可以做這樣的事情:

await page.goto('https://www.google.com/search?q=puppeteer') 

const LINKS_SELECTOR = 'a' 
const the2ndHref = await page.evaluate(selector => { 
    const allLinks = document.querySelectorAll(selector) 
    return allLinks[1].href 
}, LINKS_SELECTOR) 

console.log('the2ndHref', the2ndHref) 
+0

是的,你的解決方案的工作做得更好。謝謝! – octasimo