在Pupeteer Node.js中获取href属性

Goo*_*bot 5 node.js puppeteer

我知道常见的方法,例如evaluate捕获中的元素puppeteer,但是我很好奇为什么无法href以类似JavaScript的方法获取属性

const page = await browser.newPage();

await page.goto('https://www.example.com');

let links = await page.$$('a');
for (let i = 0; i < links.length; i++) {
  console.log(links[i].getAttribute('href'));
  console.log(links[i].href);
}
Run Code Online (Sandbox Code Playgroud)

Eke*_*wei 13

const yourHref = await page.$eval('selector', anchor => anchor.getAttribute('href'));
Run Code Online (Sandbox Code Playgroud)

但如果使用手柄,您可以

const handle = await page.$('selector');
const yourHref = await page.evaluate(anchor => anchor.getAttribute('href'), handle);
Run Code Online (Sandbox Code Playgroud)


vse*_*byt 9

await page.$$('a')返回一个带有ElementHandles的数组-这些是具有自己的特定于pepeteer的API的对象,它们没有用于HTML元素或DOM节点的常规DOM API。因此,您需要通过浏览器上下文检索属性/属性,page.evaluate()或者使用相当复杂的ElementHandles API。这是两种方式的示例:

'use strict';

const puppeteer = require('puppeteer');

(async function main() {
  try {
    const browser = await puppeteer.launch();
    const [page] = await browser.pages();

    await page.goto('https://example.org/');

    // way 1
    const hrefs1 = await page.evaluate(
      () => Array.from(
        document.querySelectorAll('a[href]'),
        a => a.getAttribute('href')
      )
    );

    // way 2
    const elementHandles = await page.$$('a');
    const propertyJsHandles = await Promise.all(
      elementHandles.map(handle => handle.getProperty('href'))
    );
    const hrefs2 = await Promise.all(
      propertyJsHandles.map(handle => handle.jsonValue())
    );

    console.log(hrefs1, hrefs2);

    await browser.close();
  } catch (err) {
    console.error(err);
  }
})();
Run Code Online (Sandbox Code Playgroud)


Phi*_*hix 8

不知道为什么会这么痛,不过前段时间遇到这个的时候就发现了。

async function getHrefs(page, selector) {
  return await page.$$eval(selector, anchors => [].map.call(anchors, a => a.href));
}
Run Code Online (Sandbox Code Playgroud)