【问题标题】:Scraping Keyword Suggestions from Google从 Google 抓取关键字建议
【发布时间】:2013-02-20 08:06:40
【问题描述】:

我目前正在从 Google 收集关键字建议。这是我正在使用的脚本:

<?php
function text_between($start,$end,$string) {
  if ($start != '') {$temp = explode($start,$string,2);} else {$temp = array('',$string);}
  $temp = explode($end,$temp[1],2);
  return $temp[0];
}
function gsscrape($keyword) {
  $keyword=str_replace(" ","+",$keyword);
  global $kw;
  $data=file_get_contents('http://suggestqueries.google.com/complete/search?output=firefox&client=firefox&hl=en-US&q='.$keyword);
  $data=explode('[',$data,3);
  $data=explode('],[',$data[2]);
  foreach($data as $temp) {
  $kw[]= text_between('"','"',$temp);
  }
}
#simple to use, just use yourscriptname.php?keywords

if ($_SERVER['QUERY_STRING']!='') {
  gsscrape($_SERVER['QUERY_STRING']);
  foreach ($kw as $keyword) {
  gsscrape($keyword);
  }

//sorted and duplicates removed
sort(array_unique($kw));

#all results echoed with break
foreach ($kw as $keywords) {
echo $keywords. "<br />";
}

}
?>

当通过 URL 直接访问时,Google 会给我这个关键字 money 的响应:

["money",["moneygram","money network","money mutual","money trees lyrics","moneyball","moneypak","money","money converter","money order","money2india"]]

但是,由于某种原因,当我在我的网站上对其进行测试时,它只是显示如下:

moneygram
moneygram

需要更改哪些内容才能像这样显示每个关键字?

moneygram, money network, money mutual, money trees lyrics, moneyball, moneypak, money, money converter, money order, money2india

【问题讨论】:

  • 你应该看看scrape-google-suggest.compunect.com这是一个开源的PHP谷歌建议抓取蜘蛛做你想要编程的事情,还有更多(本地缓存、递归蜘蛛、IP管理)即使你坚持你的代码,我链接的那个可能包含你会发现有用的功能。

标签: php web-scraping


【解决方案1】:

这是有效的 JSON,使用 json_decode 就完成了!

var_dump(json_decode('["money",["moneygram","money network","money mutual","money trees lyrics","moneyball","moneypak","money","money converter","money order","money2india"]]'));

编辑 - 完整示例;

<?php

function getKeywordSuggestionsFromGoogle($keyword) {
    $keywords = array();
    $data = file_get_contents('http://suggestqueries.google.com/complete/search?output=firefox&client=firefox&hl=en-US&q='.urlencode($keyword));
    if (($data = json_decode($data, true)) !== null) {
        $keywords = $data[1];
    }

    return $keywords;
}

var_dump(getKeywordSuggestionsFromGoogle('money'));

【讨论】:

  • 如何将它与当前脚本一起使用?结果会因关键字而异...
  • 嗯,当然..您将从谷歌返回的数据发送并作为输入到您的 json_decode.. 这真的很简单,但我会用一个完整的例子来更新..
  • 那太棒了!很抱歉给您带来麻烦,只是第一次尝试解决这些问题:)
  • 不错的功能伙伴。但是为什么它只给出 10 个结果。我试图将 num=100 放在 url 上,但没有任何反应。你能弄清楚吗:)
  • 再加20个怎么样?
【解决方案2】:

要以数组的形式获取数据,请使用:

    function gsscrape($keyword) {
      return json_decode(utf8_decode(file_get_contents('http://suggestqueries.google.com/complete/search?output=firefox&client=firefox&hl=en-US&q='.urlencode($keyword))),true);
     }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-12
    • 1970-01-01
    • 1970-01-01
    • 2018-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多