我可以使用什么正则表达式从Google搜索中提取网址?

时间:2010-01-23 09:56:48

标签: regex delphi html-parsing jvcl

我正在使用Delphi和JCLRegEx,并希望从谷歌搜索中捕获所有结果URL。我查看了HackingSearch.com,他们有一个看起来正确的RegEx示例,但是当我尝试它时,我无法获得任何结果。

我使用它类似于:

Var re:JVCLRegEx;
    I:Integer; 
Begin
  re := TJclRegEx.Create;

  With re do try
    Compile('class="?r"?>.+?href="(.+?)".*?>(.+?)<\/a>.+?class="?s"?>(.+?)<cite>.+?class="?gl"?><a href="(.+?)"><\/div><[li|\/ol]',false,false);  
    If match(memo1.lines.text) then begin
      For I := 0 to captureCount -1 do
        memo2.lines.add(captures[1]);
    end;
  finally free;
  end;
  freeandnil(re);
end;

正则表达式位于hackingsearch.com

我正在使用Delphi Jedi版本,因为每次我安装TPerlRegEx都会与这两个版本发生冲突......

4 个答案:

答案 0 :(得分:1)

Offtopic:您可以尝试Google AJAX Search API:http://code.google.com/apis/ajaxsearch/documentation/

答案 1 :(得分:1)

以下是Google搜索结果中与python tuple一词相关的部分。 (我通过在这里和那里添加新行来修改它以适应屏幕,但我测试了你的正则表达式,从Firebug显示的Google源码获取的原始字符串)。你的正则表达式没有给这个字符串匹配。

<li class="g w0">
  <h3 class="r">
    <a onmousedown="return rwt(this,'','','res','2','AFQjCNG5WXSP8xy6BkJFyA2Emg8JrFW2_g','&amp;sig2=4MpG_Ib3MrwYmIG6DbZjSg','0CBUQFjAB')" 
      class="l" href="http://www.korokithakis.net/tutorials/python">Learn <em>Python</em> in 10 minutes | Stavros's Stuff</a>
  </h3>
  <span style="display: inline-block;">
    <button class="w10">
    </button>
    <button class="w20">
    </button>
  </span>
  <span class="m">&nbsp;<span dir="ltr">- 2 visits</span>&nbsp;<span dir="ltr">- Jan 21</span></span>
  <div class="s">
  The data structures available in <em>python</em> are lists, <em>tuples</em>
   and dictionaries. Sets are available in the sets library (but are built-in in <em>
  Python</em> 2.5 and <b>...</b><br>
  <cite>
    www.korokithakis.net/tutorials/<b>
    python</b>
     - 
  </cite>
  <span class="gl">
    <a onmousedown="return rwt(this,'','','clnk','2','AFQjCNFVaSJCprC5enuMZ9Nt7OZ8VzDkMg','&amp;sig2=4qxw5AldSTW70S01iulYeA')" 
      href="http://74.125.153.132/search?q=cache:oeYpHokMeBAJ:www.korokithakis.net/tutorials/python+python+tuple&amp;cd=2&amp;hl=en&amp;ct=clnk&amp;client=firefox-a">
      Cached
    </a>
     - <button title="Comment" class="wci">
    </button>
    <button class="w4" title="Promote">
    </button>
    <button class="w5" title="Remove">
    </button>
  </span>
  </div>
  <div class="wce">
  </div>
  <!--n-->
  <!--m-->
</li>

FWIW,我想其中一个原因是这个结果中根本没有<Va>。我从Firebug复制了完整的html源代码,并试图将它与你的正则表达式相匹配 - 根本没有得到任何匹配。

Google可能会不时更改其显示结果的方式 - 在给定时间,它可能会因您的登录状态,网络历史记录等因素而异。您提出的特定正则表达式可能会为您工作目前,但从长远来看,它将难以维持。人们建议使用html解析器而不是给出正则表达式,因为他们知道解决方案不稳定。

答案 2 :(得分:0)

如果您需要使用任何语言调试正则表达式,您需要查看RegExBuddy,它不是免费的,但它会在一天内收回成本。

答案 3 :(得分:0)

class=r?>.+?href="(.+?)".*?>(.+?)<\/a>.+?class="?s"?>(.+?)<cite>.+?class="?gl"?>

现在有效。