我如何在 元素中使用python或javascript抓取数据?

问题描述 投票:0回答:1

我想从this (my game stat page)这样的网站中抓取数据,在这些网站中<canvas>元素正在呈现交互式图表,并且未在原始HTML文件中显示任何数据。检查HTML,页面似乎使用chartjs

如果我可以用python做所有事情,那将很棒,但是如果我真的需要使用一些javascript,那也将很好。

PS:我想避免使用需要额外文件的方法,例如phantomjs,但是如果这是唯一的方法,请足够慷慨地共享它:)。

javascript python python-3.x web-scraping chart.js
1个回答
0
投票

解决此问题的一种方法是通过在行1050周围的页面源中检出页面的<script>,这实际上是图表初始化的位置。图表的初始化过程中有一种重复出现的模式,其中画布元素被一一查询以获取其上下文,然后是提供图表标签和统计信息的变量。

此解决方案涵盖使用node.js,至少是具有以下模块的最新版本:

  • cheerio用于查询DOM中的元素
  • [axios用于发送http请求以获取页面源。
  • [abstract-syntax-tree以获取我们希望抓取的脚本的javascript对象树表示形式。
  • 这是下面的solution和源代码:

const cheerio = require('cheerio');

const axios = require('axios');

const { parse, each, find } = require('abstract-syntax-tree');

async function main() {

    // get the page source
    const { data } = await axios.get(
        'https://stats.warbrokers.io/players/i/5d2ead35d142affb05757778'
    );

    // load the page source with cheerio to query the elements
    const $ = cheerio.load(data);

    // get the script tag that contains the string 'Chart.defaults'
    const contents = $('script')
        .toArray()
        .map(script => $(script).html())
        .find(contents => contents.includes('Chart.defaults'));

    // convert the script content to an AST
    const ast = parse(contents);

    // we'll put all declarations in this object
    const declarations = {};

    // current key
    let key = null;

    // iterate over all variable declarations inside a script
    each(ast, 'VariableDeclaration', node => {

        // iterate over possible declarations, e.g. comma separated
        node.declarations.forEach(item => {

            // let's get the key to contain the values of the statistics and their labels
            // we'll use the ID of the canvas itself in this case..
            if(item.id.name === 'ctx') { // is this a canvas context variable?
                // get the only string literal that is not '2d'
                const literal = find(item, 'Literal').find(v => v.value !== '2d');
                if(literal) { // do we have non- '2d' string literals?
                    // then assign it as the current key
                    key = literal.value;
                }
            }

            // ensure that the variable we're getting is an array expression
            if(key && item.init && item.init.type === 'ArrayExpression') {

                // get the array expression
                const array = item.init.elements.map(v => v.value);

                // did we get the values from the statistics?
                if(declarations[key]) {

                    // zip the objects to associate keys and values properly
                    const result = {};
                    for(let index = 0; index < array.length; index++) {
                        result[array[index]] = declarations[key][index];
                    }
                    declarations[key] = result;

                    // let's make the key null again to avoid getting
                    // unnecessary array expression
                    key = null;

                } else {
                    // store the values
                    declarations[key] = array;
                }
            }

        });

    });

    // logging it here, it's up to you how you deal with the data itself
    console.log(declarations);

}

main();
© www.soinside.com 2019 - 2024. All rights reserved.