我发现自己需要能够通过反向图像查找来查询谷歌,以找到更多关于我服务器上未知内容的图像。在这里找到了一个很好的问题:php Extract Best guess for this image result from google image search?
尝试实现那里列出的方法,但最近似乎谷歌获取了您漂亮的 URL 并进行 302 重定向到看似随机生成的无意义 URL,将您带到图像搜索结果。我确保我的代码将 CURLOPT_FOLLOWLOCATION 设置为 1,但我仍然取回 302 页面的内容。这是代码:
function fetch_google($terms="sample search",$numpages=1,$user_agent='Mozilla/5.0 (Windows NT 6.1; rv:8.0) Gecko/20100101 Firefox/8.0')
{
$searched="";
for($i=0;$i<=$numpages;$i++)
{
$ch = curl_init();
$url="http://www.google.com/searchbyimage?hl=en&image_url=".urlencode($terms);
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_USERAGENT, $user_agent);
curl_setopt ($ch, CURLOPT_HEADER, 0);
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_REFERER, 'http://www.google.com/');
curl_setopt ($ch,CURLOPT_CONNECTTIMEOUT,120);
curl_setopt ($ch,CURLOPT_TIMEOUT,120);
curl_setopt ($ch,CURLOPT_MAXREDIRS,10);
curl_setopt ($ch,CURLOPT_COOKIEFILE,"cookie.txt");
curl_setopt ($ch,CURLOPT_COOKIEJAR,"cookie.txt");
$searched=$searched.curl_exec ($ch);
curl_close ($ch);
}
$xml = new DOMDocument();
@$xml->loadHTML($searched);
return $searched;
}
$content = fetch_google("http://upload.wikimedia.org/wikipedia/commons/thumb/0/0f/Grosser_Panda.JPG/1280px-Grosser_Panda.JPG",1);
echo $content."<br>";
还尝试了另一种实现方式来仅取回 URL,然后在返回的 URL 之后进行第二次 cURL 调用。同样的结果,返回 302 页面内容。这是该代码的获取 url 部分,该部分会给我一个 URL 以从中提取:
function get_furl($url)
{
$furl = false;
// First check response headers
$headers = get_headers($url);
// Test for 301 or 302
if(preg_match('/^HTTP\/\d\.\d\s+(301|302)/',$headers[0]))
{
foreach($headers as $value)
{
if(substr(strtolower($value), 0, 9) == "location:")
{
$furl = trim(substr($value, 9, strlen($value)));
}
}
}
// Set final URL
$furl = ($furl) ? $furl : $url;
return $furl;
}
非常感谢任何想法!
最佳答案
Tineye 有一个可用于反向图像搜索的 API。
http://services.tineye.com/TinEyeAPI
编辑:这是一个用 python flask 编写的用于创建您自己的图像搜索引擎的解决方案。
https://github.com/realpython/flask-image-search http://www.pyimagesearch.com/2014/12/08/adding-web-interface-image-search-engine-flask/
我知道这与谷歌无关,但在这方面,Tineye 是比谷歌更好的解决方案。也许谷歌应该收购它们,然后它们就会成为谷歌。哈哈
关于php - PHP 中的谷歌反向图像查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28102935/