在 puppeteer 中链接查询选择器

chaining queryselectors in puppteer

如何像在量角器中那样在 puppteer 中链接查询选择器?

return this.page.$$(".stop.departed").$$eval(".station",el=>el.innerText)

我得到TypeError: this.page.$$(...).$$eval is not a function

我的Html是

 <div class="stop departed">
  <div class="left">
    <div class="station">London
    </div>
    <div class="scheduled">Dept. 10:47
    </div>
  </div>    
 </div>
 <div class="stop departed">
  <div class="left">
    <div class="station">Paris
    </div>
    <div class="scheduled">Dept. 12:47
    </div>
  </div>    
 </div>

我想获取列表中的所有电台名称 ["London","Paris"]。

两种方法,page.$$(), and elementHandle.$$eval() return promises, so you must await 两种方法。

这些函数也在选择器上同时 运行 querySelectorAll(),因此您必须在 运行 进行下一个操作(或遍历所有索引)之前通过索引指定元素。

下面的例子将return第一站第一站:

const first_station = await ( await page.$$( '.stop.departed' ) )[0].$$eval( '.station', el => el[0].innerText );

console.log( first_station ); // London

或者,您可以使用以下示例获取每个站点的站点数组:

const stations = await Promise.all(
    ( await page.$$( '.stop.departed' ) ).map( el => el.$$eval( '.station', el => el.map( el => el.innerText ) ) )
);

console.log( stations.length );    // 2
console.log( stations[0].length ); // 1
console.log( stations[1].length ); // 1
console.log( stations[0][0] );     // London
console.log( stations[1][0] );     // Paris

或者如果每一站只有一个站,你可以使用:

const stations = await Promise.all(
    ( await page.$$( '.stop.departed' ) ).map( el => el.$$eval( '.station', el => el[0].innerText ) )
);

console.log( stations.length ); // 2
console.log( stations[0] );     // London
console.log( stations[1] );     // Paris