加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-15 04:17:02 所属栏目:大数据 来源:网络整理
导读:我正在尝试从Google搜索结果中提取网址.我使用Indy IdHTTP从Google获取 HTML结果,我使用 Achmad Z’s code for getting the link hrefs from the page.如何获得每个URL的真实链接目标,而不是通过Google重定向器的URL? 我试过了,但是在这段代码中我得到了“
我正在尝试从Google搜索结果中提取网址.我使用Indy IdHTTP从Google获取 HTML结果,我使用 Achmad Z’s code for getting the link hrefs from the page.如何获得每个URL的真实链接目标,而不是通过Google重定向器的URL?

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

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;

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

解决方法

在上一篇文章中,我试图解释为什么你应该使用谷歌搜索API,在这个我试着给你一个例子,希望它能在你的Delphi 7中运行.

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

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

您可以在之前提到的DxGoogleSearchApi.pas中看到网址请求,但最好是遵循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;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读