python如何抓取微博定時熱搜

不知道大家在工作無聊時,是不是總想掏出手機,刷刷微博看下熱搜在討論什麼有趣的話題,但又不方便直接打開微博瀏覽,今天就和大家分享一個有趣的小爬蟲,那就是如何定時採集微博熱搜榜&熱評,下具體的實現方法我們接下來慢慢講。

首先我們需要找到微博排行、熱度、標題,以及詳情頁的鏈接。熱搜首頁鏈接https://weibo.com/hot/search我們通過這個鏈接獲取500條數據,熱搜榜採集代碼, 然後發起請求,簡單的代碼如下

<?php
    // 要訪問的目標頁面
    $url = "https://weibo.com/hot/searc";
    $urls = "https://weibo.com/hot/searc";

    // 代理服務器(產品官網 www.16yun.cn)
    define("PROXY_SERVER", "tcp://t.16yun.cn:31111");

    // 代理身份信息
    define("PROXY_USER", "16YAQOZD");
    define("PROXY_PASS", "660237");

    $proxyAuth = base64_encode(PROXY_USER . ":" . PROXY_PASS);

    // 設置 Proxy tunnel
    $tunnel = rand(1,10000);

    $headers = implode("\r\n", [
        "Proxy-Authorization: Basic {$proxyAuth}",
        "Proxy-Tunnel: ${tunnel}",
    ]);
    $sniServer = parse_url($urls, PHP_URL_HOST);
    $options = [
        "http" => [
            "proxy"  => PROXY_SERVER,
            "header" => $headers,
            "method" => "GET",
            'request_fulluri' => true,
        ],
        'ssl' => array(
                'SNI_enabled' => true, // Disable SNI for https over http proxies
                'SNI_server_name' => $sniServer
        )
    ];
    print($url);
    $context = stream_context_create($options);
    $result = file_get_contents($url, false, $context);
    var_dump($result);

    // 訪問 HTTPS 頁面
    print($urls);
    $context = stream_context_create($options);
    $result = file_get_contents($urls, false, $context);
    var_dump($result);
?>

雖然我們獲取的數量量不大,但是也可能會遇到網站封ip的,爲保證程序的正常運行,我們可以加上代理ip,比如我們示例裏面加的億牛雲代理,有了代理ip的輔助,整體的效果會好很多。關於Python定時爬取微博熱搜示例介紹的文章就介紹到這了,更多相關Python爬取微博熱搜內容我們下次分享學習。

 

若有收穫,就點個贊吧

 
 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章