![](/img/trans.png)
[英]How to open web console like Chrome console in Visual Studio Code preview side and see JavaScript changes dynamicaly?
[英]Does the Chrome console execute things the same way as Visual Studio Code?
您的代碼存在一些問題。
首先,您嘗試訪問的頁面會動態加載其內容,因此您可能要等待使用page.waitForSelector()
將選擇器字符串指定的元素添加到DOM中:
await page.waitForSelector('#app > div > div.container > div.now-list-restautants > div > div > a > div.info-restaurant > p > i');
此外,在page.evaluate()
內部, page.evaluate()
變量jq
:
document.getElementsByTagName('head')[0].appendChild(jq); // jq is not defined
此外,您不必要地等待兩次result
。 您可以返回result
:
return result;
最后,請確保在完成爬取鏈接后使用的是browser.close()
:
await browser.close();
下面列出的其余問題與樣式有關,而與功能無關。
const arr = ... // good
var arr = ... // bad
如果要將可迭代對象轉換為數組,請使用傳播語法 ,而不是Array.from()
( source ):
[...elements] // good
Array.from(elements) // bad
您可以獲取href
使用的元素屬性href
屬性,因此,你不需要使用getAttribute('href')
:
element.querySelector('.item-content').href // good
element.querySelector('.item-content').getAttribute('href') // bad
這是一個完整的工作示例:
'use strict';
const puppeteer = require('puppeteer');
let scrape = async () => {
const browser = await puppeteer.launch({headless: false});
const page = await browser.newPage();
await page.goto('https://www.now.vn/ho-chi-minh/food/danh-sach-dia-diem-phuc-vu-ca-phe,nuoc-ep-sinh-to,16,70-giao-tan-noi');
await page.waitForSelector('#app > div > div.container > div.now-list-restautants > div > div > a > div.info-restaurant > p > i');
const result = await page.evaluate(() => {
// document.getElementsByTagName('head')[0].appendChild(jq);
const data2 = [];
const elements = document.querySelector('#app > div > div.container > div.now-list-restautants > div').children;
const arr = [...elements];
const regex = '';
arr.shift();
arr.forEach((element, index) => {
const tagi = document.querySelector('#app > div > div.container > div.now-list-restautants > div > div:nth-child(' + (index + 2) + ') > a > div.info-restaurant > p > i');
if (element.contains(tagi)) {
data2.push(element.querySelector('.item-content').href);
}
});
return data2;
});
await browser.close();
return result;
};
scrape().then(value => {
console.log(value);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.