【问题标题】:Can't find class inside class在课堂内找不到课堂
【发布时间】:2021-03-10 10:49:12
【问题描述】:

我有这个html结构

<div class="parent">
     <span class="children">This is children text</span>
     <br>
     <span>another text</span>
</div>
<div class="parent">
     <span class="children">This is children text</span>
     <br>
     <span>another text</span>
</div>

我尝试用 puppeteer 解析它

result.parents = []
let parents = await page.$$('.parent')
for (let i=0; i<parents.length; i++) {
   let chd = await parents[i].$eval('.children', ele => ele.innerText)
   result.parents.push(chd)
}

该代码给出错误结果

Could not resolve the browser instance =&gt; Error: Error: failed to find element matching selector ".children"

为什么?

【问题讨论】:

    标签: node.js puppeteer


    【解决方案1】:

    我无法使用此测试脚本重现该问题。也许您错过了问题中的一些细节?

    import puppeteer from 'puppeteer';
    
    const browser = await puppeteer.launch();
    
    const html = `
      <!doctype html>
      <html>
        <head><meta charset='UTF-8'><title>Test</title></head>
        <body>
    
          <div class="parent">
               <span class="children">This is children text</span>
               <br>
               <span>another text</span>
          </div>
          <div class="parent">
               <span class="children">This is children text</span>
               <br>
               <span>another text</span>
          </div>
    
        </body>
      </html>`;
    
    try {
      const [page] = await browser.pages();
    
      await page.goto(`data:text/html,${html}`);
    
      const result = {};
      result.parents = [];
      const parents = await page.$$('.parent');
      for (let i = 0; i < parents.length; i++) {
         const chd = await parents[i].$eval('.children', ele => ele.innerText);
         result.parents.push(chd);
      }
    
      console.log(result);
    } catch (err) { console.error(err); } finally { await browser.close(); }
    

    输出:

    { parents: [ 'This is children text', 'This is children text' ] }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-31
      • 1970-01-01
      • 1970-01-01
      • 2019-07-03
      • 1970-01-01
      • 1970-01-01
      • 2019-01-29
      相关资源
      最近更新 更多