微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在网络抓取中获取<span>文本

如何解决在网络抓取中获取<span>文本

我正在使用Puppeteer和jsDOM抓取以下站点https://www.lcfc.com/matches/results

我想要每场比赛的球队名称,所以在控制台上我使用以下名称

document.querySelectorAll('.match-item__team-container span')
  .forEach(element => console.log(element.textContent));

在控制台上,名称显示为ok,但是当我在代码中使用此名称时,它什么也不会返回。

这是我的代码

const puppeteer = require('puppeteer');
const jsdom = require('jsdom');
(async () => {
  try {
    const browser = await puppeteer.launch() ;
    const page = await browser.newPage();
    const response = await page.goto('https://www.lcfc.com/matches/results');
    const body = await response.text();
    const { window: { document } } = new jsdom.JSDOM(body);

    document.querySelectorAll('.match-item__team-container span')
      .forEach(element => console.log(element.textContent));

    await browser.close();
  } catch (error) {
    console.error(error);
  }
})();

我没有任何错误。有什么建议吗?谢谢。

我现在尝试使用此代码,但仍然无法正常工作。我显示代码和控制台图片

const puppeteer = require('puppeteer');
(async () => {
  try {
    const browser = await puppeteer.launch() ;
    const page = await browser.newPage();
    await page.waitForSelector('.match-item__team-container span');
    const data = await page.evaluate(() => {
      document.querySelectorAll('.match-item__team-container span')
          .forEach(element => console.log(element.textContent));
    });
    //listen to console events in the chrome tab and log it in nodejs process
    page.on('console',consoleObj => console.log(consoleObj.text()));

    await browser.close();
  } catch (error) {
    console.log(error);
  }
})();

enter image description here

解决方法

以伪造方式进行操作,并在等待选择器通过evaluate出现之后,使用waitForSelector来运行代码

await page.waitForSelector('.match-item__team-container span');
const data = await page.evaluate(() => {
  document.querySelectorAll('.match-item__team-container span')
      .forEach(element => console.log(element.textContent));
    //or return the values of the selected item
   return somevalue; 
});
//listen to console events in the chrome tab and log it in nodejs process
page.on('console',consoleObj => console.log(consoleObj.text()));

evaluate在chrome的活动标签内运行代码,因此您不需要jsDOM来解析响应。

更新 新的超时问题是因为页面加载时间太长:请使用{timeout : 0}

const data = await page.evaluate(() => {
  document.querySelectorAll('.match-item__team-container span')
      .forEach(element => console.log(element.textContent));
    //or return the values of the selected item
   return somevalue; 
},{timeout:60000});

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。