代码之家  ›  专栏  ›  技术社区  ›  Vega

如何从DOM获取所有链接?

  •  10
  • Vega  · 技术社区  · 6 年前

    根据 https://github.com/GoogleChrome/puppeteer/issues/628 ,我应该能够从中获取所有链接 <a href=“xyz”> 使用这一行:

    const hrefs = await page.$$eval('a', a => a.href);
    

    但当我尝试一个简单的:

    console.log(hrefs)
    

    我只得到:

    http://example.de/index.html
    

    。。。作为输出,这意味着它只能找到1个链接?但是该页面在源代码/DOM中肯定有12个链接。为什么它找不到它们?

    最小示例:

    'use strict';
    const puppeteer = require('puppeteer');
    
    crawlPage();
    
    function crawlPage() {
        (async () => {
    	
    	const args = [
                "--disable-setuid-sandbox",
                "--no-sandbox",
                "--blink-settings=imagesEnabled=false",
            ];
            const options = {
                args,
                headless: true,
                ignoreHTTPSErrors: true,
            };
    
    	const browser = await puppeteer.launch(options);
            const page = await browser.newPage();
    	await page.goto("http://example.de", {
                waitUntil: 'networkidle2',
                timeout: 30000
            });
         
    	const hrefs = await page.$eval('a', a => a.href);
            console.log(hrefs);
    		
            await page.close();
    	await browser.close();
    		
        })().catch((error) => {
            console.error(error);
        });;
    
    }
    2 回复  |  直到 4 年前
        1
  •  34
  •   Miguel Calderón    6 年前

    在您使用的示例代码中 page.$eval page.$$eval 。因为前者使用 document.querySelector 而不是 document.querySelectorAll ,您描述的行为是预期的行为。

    此外,您应该更改 pageFunction $$eval 参数:

    const hrefs = await page.$$eval('a', as => as.map(a => a.href));
    
        2
  •  3
  •   Grant Miller    4 年前

    这个 page.$$eval() 方法运行 Array.from(document.querySelectorAll(selector)) 并将其作为第一个参数传递给page函数。

    自从 a 在表示数组的示例中,您需要指定要获取数组的哪个元素 href 或者你需要 map 所有的 href 数组的属性。

    第页$$评估()

    const hrefs = await page.$$eval('a', links => links.map(a => a.href));
    

    或者,您也可以使用 page.evaluate() 或者两者的结合 page.$$() ,则, elementHandle.getProperty() jsHandle.jsonValue() 实现页面中所有链接的数组。

    页评估()

    const hrefs = await page.evaluate(() => {
      return Array.from(document.getElementsByTagName('a'), a => a.href);
    });
    

    第页$$()/元素句柄。getProperty()/jsHandle。jsonValue()

    const hrefs = await Promise.all((await page.$$('a')).map(async a => {
      return await (await a.getProperty('href')).jsonValue();
    }));