【问题标题】:What would be the best way to collect the titles (in bulk) of a subreddit收集 subreddit 标题(批量)的最佳方式是什么
【发布时间】:2016-11-07 02:50:29
【问题描述】:

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

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

由于我不想承诺找出 90% 的方法都行不通,我想问是否有人可以指出我正确的语言方向和附加功能,例如 Python 所需的任何软件。

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

所以我的问题是

收集(批量)标题的最佳方式是什么? 子版块?

或者如果这太主观了

如何检索和存储 subreddit 的所有帖子标题?

最好需要:

  • 执行超过 1 页的 (25) 个结果
  • 保存为 .txt 文件

提前致谢。

【问题讨论】:

  • API 是这里的关键要素,而不是使用的语言。查看 API 以确保可以返回您想要的数据。

标签: php python automation bots reddit


【解决方案1】:

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);

【讨论】:

  • 感谢@Jamie,如果您能对 curl 位做一个快速的解释,请让我非常了解其余部分。
猜你喜欢
  • 2019-07-17
  • 2014-01-23
  • 1970-01-01
  • 1970-01-01
  • 2014-08-19
  • 2021-07-14
  • 2013-10-04
  • 2011-05-07
  • 1970-01-01
相关资源
最近更新 更多