我正在尝试使用page.$$eval()
从 a 获取数据<ul>
,将值存储在两个数组中,然后遍历数组以将数据放入键/值对中。我正在努力将数据放入数组中。
HTML 如下所示:
<ul class="b-profile__sections">
<li class="b-profile__sections__item">
<span class="b-profile__sections__link">
<span class="b-profile__sections__count">585</span>
<span class="b-profile__sections__name"> Posts </span>
</span>
</li>
<li class="b-profile__sections__item">
<span class="b-profile__sections__link m-no-hover">
<span class="b-profile__sections__count">110.3K</span>
<span class="b-profile__sections__name"> Likes </span>
</span>
</li>
</ul>
我的代码:
let user = {};
let properties = [];
let values = [];
await page.$$eval('.b-profile__sections__name', (elems, properties) => elems.forEach(elem => {
properties.push(elem.innerText); // push result into array
}), properties) // array passed as argument to page.$$eval()
await page.$$eval('.b-profile__sections__count', (elems, values) => elems.forEach(elem => {
values.push(elem.innerText); // push result into array
}), values) // array passed as argument to page.$$eval()
for (let i = 0; i < properties.length; i++) {
user[properties[i]] = values[i] //iterate through arrays to make key/value pairs
}
错误:
Error: Evaluation failed: ReferenceError: values is not defined
at __puppeteer_evaluation_script__:2:37
at Array.forEach (<anonymous>)
at __puppeteer_evaluation_script__:1:19
或者:
Error: Evaluation failed: TypeError: Cannot read property 'push' of undefined
at __puppeteer_evaluation_script__:2:44
at Array.forEach (<anonymous>)
at __puppeteer_evaluation_script__:1:27
我猜这与浏览器(传递给的函数page.$$eval()
)/Node.js(两个数组)上下文有关。有没有更好的办法?