我正在尝试从whitepages.com 中抓取地址,但我的抓取工具每次运行时都会抛出此错误。
(节点:11389)UnhandledPromiseRejectionWarning:TypeError:无法读取未定义的属性“getProperty”
这是我的代码:
const puppeteer = require('puppeteer')
async function scrapeAddress(url){
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto(url,{timeout: 0, waitUntil: 'networkidle0'});
const [el]= await page.$x('//*[@id="left"]/div/div[4]/div[3]/div[2]/a/h3/span[1]');
// console.log(el)
const txt = await el.getProperty('textContent');
const rawTxt = await txt.jsonValue();
console.log({rawTxt});
browser.close();
}
scrapeAddress('https://www.whitepages.com/business/CA/San-Diego/Cvs-Health/b-1ahg5bs')
经过一番调查后,我意识到 el 变量返回为未定义,我不确定为什么。我已经尝试使用相同的代码从其他站点获取元素,但仅对于此站点我收到此错误。
我尝试了完整和短的 XPath 以及其他周围元素,该网站上的所有内容都会引发此错误。
为什么会发生这种情况?有什么办法可以解决它吗?
最佳答案
您可以尝试将所有内容包装在 try catch block 中,否则尝试使用 then() 解开 Promise。
(async() => {
const browser = await puppeteer.launch();
try {
const page = await browser.newPage();
await page.goto(url,{timeout: 0, waitUntil: 'networkidle0'});
const [el]= await page.$x('//*[@id="left"]/div/div[4]/div[3]/div[2]/a/h3/span[1]');
// console.log(el)
const txt = await el.getProperty('textContent');
const rawTxt = await txt.jsonValue();
console.log({rawTxt});
} catch (err) {
console.error(err.message);
} finally {
await browser.close();
}
})();
关于javascript - Puppeteer 错误,在抓取白页时无法读取未定义的属性 'getProperty',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59798731/