如何从Google搜索结果中提取目标网址?

Dan*_*axa 5 delphi delphi-7

我正在尝试从Google搜索结果中提取网址.我使用Indy IdHTTP从Google获取HTML结果,并使用Achmad Z的代码从页面获取链接href.如何获取每个网址的真实链接目标,而不是通过Google重定向程序的网址?


我试过了,但是在这段代码中我得到了"操作数不适用"的错误:

function ToUTF8Encode(str: string): string;
var
  b: Byte;
begin
  for b in BytesOf(UTF8Encode(str)) do
  begin
    Result := Format('%s%s%.2x', [Result, '%', b]);
  end;
end;
Run Code Online (Sandbox Code Playgroud)

我使用Delphi 7和Indy 9.00.10.也许indy update会有帮助吗?

TLa*_*ama 5

如果我做得对,那么您正尝试使用TIdHTTP.Get方法获取Google搜索结果.如果是这样,那么
您应该专注于某些Google Search API实施,因为

  1. 以这种方式获取结果是不可能的,因为您无法访问搜索结果所在的iframe内的文档,因此在这种情况下您不会通过使用HTTP GET获得任何搜索结果(或者至少我没有听说过可以做到这一点的请求)
  2. 这是违反Google政策的,您应该使用正确的Google搜索API,例如Google SOAP Search API,还有几种类型的Google搜索API用于各种目的

您可以找到here包含demoGoogle Search API代码的Delphi包装器.我在Windows 7/64上使用Delphi 2009对它进行了测试,它对我来说很好用.


TLa*_*ama 4

在上一篇文章中,我试图解释为什么应该使用 Google Search API,在这篇文章中,我将尝试为您提供一个示例,希望它能在您的 Delphi 7 中工作。

你需要有SuperObject(Delphi 的 JSON 解析器),我已经使用过this version(此时最新的)。那么你需要印地;如果可能的话,最好的办法是升级到最新版本。我已经使用了 Delphi 2009 附带的方法,但我认为该TIdHTTP.Get方法非常重要,它在您的 9.00.10 版本中也必须正常工作。

现在您的表单上需要一个列表框和一个按钮,下面的代码和一点运气(为了兼容性:)

您可以在前面提到的 DxGoogleSearchApi.pas 中看到 URL 请求构建,但最好遵循Google Web Search API reference. 在 DxGoogleSearchApi.pas 中,您可以获取灵感,例如如何获取多个页面。

所以以此为灵感

uses
  IdHTTP, IdURI, SuperObject;

const
  GSA_Version = '1.0';
  GSA_BaseURL = 'http://ajax.googleapis.com/ajax/services/search/';

procedure TForm1.GoogleSearch(const Text: string);
var
  I: Integer;
  RequestURL: string;
  HTTPObject: TIdHTTP;
  HTTPStream: TMemoryStream;
  JSONResult: ISuperObject;
  JSONResponse: ISuperObject;
begin
  RequestURL := TIdURI.URLEncode(GSA_BaseURL + 'web?v=' + GSA_Version + '&q=' + Text);

  HTTPObject := TIdHTTP.Create(nil);
  HTTPStream := TMemoryStream.Create;

  try
    HTTPObject.Get(RequestURL, HTTPStream);
    JSONResponse := TSuperObject.ParseStream(HTTPStream, True);

    if JSONResponse.I['responseStatus'] = 200 then
    begin
      ListBox1.Items.Add('Search time: ' + JSONResponse.S['responseData.cursor.searchResultTime']);
      ListBox1.Items.Add('Fetched count: ' + IntToStr(JSONResponse['responseData.results'].AsArray.Length));
      ListBox1.Items.Add('Total count: ' + JSONResponse.S['responseData.cursor.resultCount']);
      ListBox1.Items.Add('');

      for I := 0 to JSONResponse['responseData.results'].AsArray.Length - 1 do
      begin
        JSONResult := JSONResponse['responseData.results'].AsArray[I];
        ListBox1.Items.Add(JSONResult.S['unescapedUrl']);
      end;
    end;

  finally
    HTTPObject.Free;
    HTTPStream.Free;
  end;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  GoogleSearch('Delphi');
end;
Run Code Online (Sandbox Code Playgroud)