首页 > 解决方案 > 无法使用 puppeteer 从网站中提取某些文本元素。想知道为什么会这样以及如何解决它

问题描述

我正在尝试构建一个网络爬虫来为一个项目抓取我的 venmo 页面。我可以让 puppeteer 打开页面并导航到我的页面,以及通过存储 chrome 用户数据登录,但我试图提取我收到钱的时间和该交易的价值。特别是我最近的交易。

我知道刮板可以工作,并向我返回值,因为我创建了一个新的 document.querySelector,它只是从网站顶部刮掉了我的名字。当我在没有 .innerHTML 或 .innerText 的情况下运行脚本时,我没有抛出任何错误,但我正在寻找的两个值(不是我的名字)返回 null,但我的名字返回给我。当我添加 .innerHTML 或 .innerText 时,我收到一个错误

valuation failed: TypeError: Cannot read property 'innerHTML' of null
at __puppeteer_evaluation_script__:4:58

我已经在检查元素的控制台中运行了我的元素,它们都返回给我,所以我无法理解为什么网页上的控制台会返回它们,但我的脚本不会。不仅仅是用 puppeteer 创建的 Chromium 窗口让我感到困惑,因为我也在该控制台中输入了 document.querySelector 并且它返回了它应该返回的内容。

const puppeteer = require('puppeteer');

//sets url to nav to 
const url = 'https://venmo.com/user';

(async () =>  {

//open broswer window and opens a new page
const browser = await puppeteer.launch({headless: false, args: ["--user- 
data-dir=./Google/Chrome/User Data/"]}); 
try{
const page = await browser.newPage();

//sets view to 1920x1080
await page.setViewport({ width: 1280, height: 720});

//navigates to the specified url
await page.goto(url,{waitUntil: 'domcontentloaded'});

//playing with wait states incase the document wasnt loading correctly
await page.waitFor(1000);

//function for evaluating the webpage
const  data = await page.evaluate(() => {

    let amount =  
    document.querySelector('span.bold.medium.green').innerHTML
    let timePayed = document.querySelector('a.grey_link').innerHTML

    //this function prints my name 
    let test = document.querySelector('span.bold').innerHTML

    return { 
    amount,
    timePayed,
    test
    }
}); 


//displays the data scraped
 console.log(data);
}
catch(err) {
     console.error(err.message);
}


debugger;

await browser.close();

})();

标签: javascriptpuppeteer

解决方案


推荐阅读