Skip to main content
 首页 » 编程设计

php之收集 subreddit 标题(批量)的最佳方式是什么

2024年10月17日21dudu

我想收集 subreddit 上所有帖子的标题,我想知道最好的方法是什么?

我环顾四周,发现了一些关于 Python 和机器人的内容。我还简要了解了 API,但不确定该往哪个方向走。

因为我不想 promise 找出 90% 的方法都行不通,所以我问是否有人可以为我指出正确的语言方向和额外的东西,比如 Python 所需的任何软件,例如 pip。

我自己的经验是使用 PHP 等网络语言,所以我最初认为网络应用程序可以解决问题,但我不确定这是否是最佳方式以及如何实现。

所以我的问题是

What would be the best way to collect the titles (in bulk) of a subreddit?

或者如果那太主观了

How do I retrieve and store all the post titles of a subreddit?

最好需要:

  • 做超过 1 页的 (25) 个结果
  • 保存到 .txt 文件

提前致谢。

请您参考如下方法:

PHP;在 25 行中:

$subreddit = 'pokemon'; 
$max_pages = 10; 
 
// Set variables with default data 
$page = 0; 
$after = ''; 
$titles = ''; 
do { 
    $url = 'http://www.reddit.com/r/' . $subreddit . '/new.json?limit=25&after=' . $after; 
 
    // Set URL you want to fetch 
    $ch = curl_init($url); 
 
    // Set curl option of of header to false (don't need them) 
    curl_setopt($ch, CURLOPT_HEADER, 0); 
 
    // Set curl option of nobody to false as we need the body 
    curl_setopt($ch, CURLOPT_NOBODY, 0); 
 
    // Set curl timeout of 5 seconds 
    curl_setopt($ch, CURLOPT_TIMEOUT, 5); 
 
    // Set curl to return output as string 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
 
    // Execute curl 
    $output = curl_exec($ch); 
 
    // Get HTTP code of request 
    $status = curl_getinfo($ch, CURLINFO_HTTP_CODE); 
 
    // Close curl 
    curl_close($ch); 
 
    // If http code is 200 (success) 
    if ($status == 200) { 
        // Decode JSON into PHP object 
        $json = json_decode($output); 
        // Set after for next curl iteration (reddit's pagination) 
        $after = $json->data->after; 
        // Loop though each post and output title 
        foreach ($json->data->children as $k => $v) { 
            $titles .= $v->data->title . "\n"; 
        } 
    } 
    // Increment page number 
    $page++; 
// Loop though whilst current page number is less than maximum pages 
} while ($page < $max_pages); 
 
// Save titles to text file 
file_put_contents(dirname(__FILE__) . '/' . $subreddit . '.txt', $titles);