【问题标题】:AJAX request in Python to get dynamic content in a pagePython中的AJAX请求以获取页面中的动态内容
【发布时间】:2021-07-19 14:41:27
【问题描述】:

我想以编程方式从 URL https://www.speedrun.com/games#orderby=mostruns 检索运行次数最多的前 100 个视频游戏列表

该页面中的列表是通过 AJAX 请求填充的 HTML 模板(如果我理解正确的话)。

这是我认为它检索游戏的 HTML 代码的一部分:

function getGames(start = 0)
    {
        var hash = getHash();
        if (!hash['orderby']) hash['orderby'] = 'mostactive';
        if (!hash['platform']) hash['platform'] = '';
        if (!hash['title']) hash['title'] = '';
        else $('#title').attr('type', 'text');

        $('#platform').val(hash['platform'].replace('&', '&'));
        $('#orderby').val(hash['orderby']);
        $('#title').val(hash['title'].replace(/\+/g, ' '));

        if (hash['unofficial'] == 'on') $("#checkbox-unofficial").prop("checked", true);
        else if (hash['unofficial'] == 'off') $("#checkbox-unofficial").prop("checked", false);

        $('.col-loadmore').hide();
        $('#spinner').show();

        ajax_users = $.get('/ajax_games.php?game=&platform=' + hash['platform'].replace('&', 'ampersand') + '&unofficial=' + ($("#checkbox-unofficial").prop("checked") ? 'on' : 'off') + '&orderby=' + hash['orderby'] + '&title=' + hash['title'] + '&series=&start=' + start, function(data) {
            $('#list').append(data);
            $('#spinner').hide();

            $('[data-toggle="tooltip"]').tooltip();
            initTimes($('#list'));
            alignImagesTimer();
            resizeListCells();
        });
    }

我想从我的 python 解释器调用该 AJAX 请求,并获取一个数组,其中包含指向前 100 个视频游戏的网页的链接(即['https://www.speedrun.com/sm64', 'https://www.speedrun.com/mc', ...]

我该怎么做?

【问题讨论】:

    标签: javascript python ajax


    【解决方案1】:

    您需要在 Python 中发出 HTTP 请求,我推荐使用 requests 库来实现此目的。

    import requests
    
    url = "https://www.speedrun.com/ajax_games.php?game=&platform=&unofficial=off&orderby=mostruns&title=&series=&start=0"
    
    response = requests.get(url)
    
    print(response.text)
    

    这是一个例子,这段代码已经运行和测试过。

    现在,需要注意的是,此端点返回原始 HTML,您需要像 BeautifulSoup 这样的解析库来帮助您清理数据并获取您正在寻找的那些 URL。

    我会做某种循环,比如“获取所有带有属性 data-url=portal 的 A 标签,并从标签中获取 href”。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-11
      • 2021-12-23
      • 2012-11-22
      • 1970-01-01
      相关资源
      最近更新 更多