问题
如何自动抓取多页结果?
回答
有时您可能会发现抓取多页用户结果并将其放入 JSON 文件很方便。为此,我创建了一个 PHP 脚本,将其粘贴在下面。
<?php
$resource = ''; // put the name of the endpoint here, for example organizations, tickets
$start_page = 1; // first page you want to load
$end_page = 10; // last page you want to load (it could take a while if too big)
$subdomain = ''; // your zendesk subdomain
$userpwd = ''; // your zendesk username and password, or username/token and api token. - {username}/token:{token} or {username}:{password}
function makerequest($url, $userpwd) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERPWD, $userpwd);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_VERBOSE, TRUE);
$result = curl_exec($ch);
if (curl_errno($ch)) $result = curl_error($ch);
curl_close($ch);
return $result;
}
function getpages($resource, $start_page, $end_page, $userpwd, $subdomain){
$url = isset($url) ? $url : "https://$subdomain.zendesk.com/api/v2/$resource.json";
$i = $start_page;
$array = Array();
while (1) {
if ($i > $end_page) {
$file = fopen("results.json", "w") or exit("Unable to open file!");
fwrite($file, json_encode(array($resource => $array)));
fclose($file);
break;
}
$results = json_decode(makerequest($url, $userpwd));
$array = array_merge($array, $results->$resource);
$url = $results->next_page;
$i++;
}
}
getpages($resource, $start_page, $end_page, $userpwd, $subdomain);
?>
下载此脚本或将其复制粘贴到名为 pginate.php的文件中。 按照脚本注释中的说明,在开头填写变量 $resource、$start_page、$end_page、$subdomain和 $userpwd。
然后,导航到您下载文件的文件夹,从终端运行命令 php pginate.php, 以便在一个名为 results.json的文件中使用您的结果创建新文件。文件将覆盖而不是附加。
收到结果后,您可以根据需要进行处理。此信息有助于查找数组中的唯一条目和重复条目。为此,将结果输出到 results.json 文件中,然后运行以下两个命令之一,第一个显示唯一结果的计数,第二个显示实际唯一值:
cat results.json | jq '.' | grep '"id"' > sort > uniq -c > uniq.txt cat results.json | jq '.' | grep '"id"' > sort > uniq > uniq.txt
要使用这些命令,您还需要安装 jq,可从以下网址下载: https://stedolan.github.io/jq/下载。
此外,此信息可用于导出数据以便导入新系统。
免责声明:本文仅供说明之用。Zendesk 不支持代码,不保证代码质量,也不针对第三方技术(例如 JavaScript、jQuery 或 CSS)提供支持。如有任何问题,请将其发布在评论部分,或尝试在线搜索解决方案。
翻译免责声明:本文章使用自动翻译软件翻译,以便您了解基本内容。 我们已采取合理措施提供准确翻译,但不保证翻译准确性
如对翻译准确性有任何疑问,请以文章的英语版本为准。