【问题标题】:Web scraping, i can't select the tags that i want网页抓取,我无法选择我想要的标签
【发布时间】:2020-05-14 08:56:17
【问题描述】:

我试图做一些网络抓取,但我发现了一个问题,我有这个 JS 脚本:

const request = require('request');
const cheerio = require('cheerio');
const url = 'https://www.sisal.it/scommesse-matchpoint?filtro=0&schede=man:1:21' // this is an 
italian betting site

request( url, (error, response, html) => {
   if (!error && response.statusCode == 200) {
      const $ = cheerio.load(html);

      let squadre = $("div"); 
      console.log(squadre.text())
   }
})

这将返回一个非常长的字符串,其中包含所有网站的 div 文本,但在此字符串中没有我想要的文本。我做了这个脚本是因为做了之后:

const $("div.*class*")

即使选择器是正确的,它也没有返回任何东西,你对我为什么不能选择我想要的 div 有任何想法吗?

【问题讨论】:

    标签: javascript html node.js xml web-scraping


    【解决方案1】:

    这个页面是动态创建的,也就是说,如果你用cheerio发出请求,你会得到SPA的样板代码,以及你以后需要上传的数据。
    要抓取此类网站,您需要比 Cheerio 更先进的东西。
    易于使用的选项 - puppeteer
    代码看起来像这样:

    (async() => {
      const browser = await puppeteer.launch();
      const page = await browser.newPage();
    
      // Use here waitUntil to wait until additional requests would be made and the page would be fully loaded.
      await page.goto('https://www.sisal.it/scommesse-matchpoint?filtro=0&schede=man:1:21', {waitUntil: 'networkidle2'});
    
      const data = await page.evaluate(() => {
         // Make here all your JS actions and return JSON.stringify data.
         // You can access DOM with document.querySelector
         // and other JS methods for DOM manipulation
         return JSON.stringify({})
      });
    
      await browser.close()
    })()
    

    只需使用 puppeteer API 并找出处理此任务的方法。

    【讨论】:

    • 谢谢!据我所知,我知道动态创建的数据没有显示在网站的检查页面上,我错了吗?
    • 你是完全正确的。动态数据稍后会上传,因此在您的报废代码中,您可以等待页面完全加载或等待某些选择器可用。例如await page.waitForSelector('#myId')。但请确保站点加载速度超过 30 秒,因为在默认配置中,puppeteer 将在 30 秒超时后关闭连接。您可以在配置中更改此行为。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-29
    • 1970-01-01
    • 1970-01-01
    • 2020-04-05
    相关资源
    最近更新 更多