簡體   English   中英

Python 中的 AJAX 請求以獲取頁面中的動態內容

[英]AJAX request in Python to get dynamic content in a page

我想以編程方式從 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', ...] )

我怎樣才能做到這一點?

您需要在 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”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM