我猜你已经知道这一点,因为你说你已经从汽车条目本身获取数据,但一个好的开始是剖析页面的 DOM 并查看是否有任何元素可以用来跳转迅速地。大多数浏览器都有页面检查工具来帮助解决这个问题。
在这种情况下,<div id="content"> 可以很好地发挥作用。您会注意到它包含一组带有所需链接的表格和一个<div>,其中包含告诉我们有多少页的文本。
免责声明,但自从我使用 PHP 以来已经有好几年了,我还没有测试过它,所以它可能既不正确也不是最优的,但它应该能让你开始。您需要将这些功能联系在一起(我这样做有什么乐趣?)以实现您想要的,但这些应该获取所需的数据。
您将在每个页面上使用 DOM,以便获取 DOMDocument:
function get_page_document($index) {
$content = file_get_contents("http://www.sayuri.co.jp/used-cars/page:{$index}");
$document = new DOMDocument;
$document->loadHTML($content);
return $document;
}
您需要知道总共有多少页才能迭代它们,所以抓住它:
function get_page_count($document) {
$content = $document->getElementById('content');
$count_div = $content->childNodes->item($content->childNodes->length - 4);
$count_text = $count_div->firstChild->textContent;
if (preg_match('/Page \d+ of (\d+)/', $count_text, $matches) === 1) {
return $matches[1];
}
return -1;
}
有点难看,但是内容容器中的每个<table> 中都有链接。把它们撕下来,然后把它们排成一个数组。如果您使用链接本身作为键,则无需担心重复,因为它们只会重写相同的键值。
function get_page_links($document) {
$content = $document->getElementById('content');
$tables = $content->getElementsByTagName('table');
$links = array();
foreach ($tables as $table) {
if ($table->getAttribute('class') === 'itemlist-table') {
// table > tbody > tr > td > a
$link = $table->firstChild->firstChild->firstChild->firstChild->getAttribute('href');
// No duplicates because they just overwrite the same entry.
$links[$link] = "http://www.sayuri.co.jp{$link}";
}
}
return $links;
}
也许也很明显,但是如果此站点更改其格式,这些将会中断。你最好问问他们是否有 REST API 或其他一些可供长期使用的 API,不过我猜你不会太在意它是否只是一个用于修补的个人项目。
希望它能帮助你朝着正确的方向前进。