最近在研究使用QueryList做php爬虫,需求是爬取百度搜索后的结果。
遇到的问题是百度搜索出来的结果都是https://www.baidu.com/link?url=开头的url地址,需要得到它跳转的真实地址才能爬取到具体数据,那么如何获取到百度搜索结果的真实url地址呢?于是研究了下它的跳转逻辑。
当我们拿到百度某个链接时,显示的是一个链接:
https://www.baidu.com/link?url=6gIGyPY85oEU1YxJVj0W4RGksM0YYY6qWvgqFYXZHuhFQWU54Fwd4qdAzIGPb70t
跳转后的链接是:
http://www.feishuai.vip
使用php得到百度搜索结果真实url地址,实现代码案例如下:
protected function getRealURL($url)
{
if (empty($url)) return $url;
$header = get_headers($url, 1);
var_dump($header);
if (strpos($header[0], '301') || strpos($header[0], '302')) {
if (is_array($header['Location'])) {
//return $header['Location'][count($header['Location'])-1];
return $header['Location'][0];
} else {
return $header['Location'];
}
} else {
return $url;
}
}