如何用Delphi的TIdHTTP、TIdCookieManager自动接受Google Finance Cookie
使用环境
- Delphi XE7
- Indy 10.6.0.5169
当前代码实现
创建TIdHTTP组件
FHTTP := TIdHTTP.Create(NIL); FHTTP.Request.Connection := 'close'; FHTTP.IOHandler := CreateSSLIOHandler; FHTTP.ConnectTimeout := 0; FHTTP.ReadTimeout := 0; FCookieManager := TIdCookieManager.Create; FHTTP.CookieManager := FCookieManager;
请求Google Finance页面代码
FExchange := 'NASDAQ'; vUrl := 'https://www.google.com/finance/quote/' + FTicker + ':' + FExchange + '?hl=en'; vSL := TStringList.Create; try try FHTTP.AllowCookies := True; FHTTP.HandleRedirects := True; vSL.Text := FHTTP.Get(vURL); // 后续处理代码 .......
问题现象
请求Google Finance页面时,响应始终是Cookie同意页,无法获取实际报价页面。
更新信息
已添加OnNewCookie事件处理程序并将VAccept设为True,捕获到以下Cookie:
SOCS SOCS=CAAaBgiArsumBg; Path=/; Domain=google.com; Secure; Max-Age=34127999; Expires=Sat, 07-Sep-2024 09:42:50 GMT __Secure-ENID __Secure-ENID=13.SE=ioKJcdGZB8gJCJYvq5OUqdA3WEcFO-rRgj7elSr3t7gPbrLKhtYqo7eUw3Cwp-Q3L8ODN_NVpJXSqBIePZNmGBfxXRvDmf0zkqrHu5uRZifeaB6SSfN4P2P7LzMk_Z4h_opf9GfsOhF9kVrIE5lFHUuLXoTECeXMlSPDfJ0Txi4; Path=/; Domain=google.com; Secure; HttpOnly; Max-Age=34186697; Expires=Sun, 08-Sep-2024 02:01:08 GMT CONSENT CONSENT=PENDING+701; Path=/; Domain=google.com; Secure; Max-Age=63071999; Expires=Fri, 08-Aug-2025 09:42:50 GMT
但问题仍未解决。
解决方案
核心问题在于CONSENT Cookie的PENDING+701值,这表示Cookie同意状态未确认。Google需要明确的同意标识才会返回实际页面,需手动设置CONSENT Cookie为已同意的值,并模拟浏览器请求行为。
具体操作步骤
手动添加已确认的CONSENT Cookie
先通过浏览器访问Google Finance,在开发者工具的「Application -> Cookies」中复制CONSENT的实际值,然后在代码中手动添加该Cookie:var LCookie: TIdCookie; begin FCookieManager := TIdCookieManager.Create; // 创建并添加CONSENT Cookie LCookie := TIdCookie.Create(nil); try LCookie.Name := 'CONSENT'; LCookie.Value := 'YES+cb.20210328-17-p0.en-GB+FX+917'; // 替换为浏览器中获取的真实值 LCookie.Domain := 'google.com'; LCookie.Path := '/'; LCookie.Secure := True; LCookie.Expires := Now + 63071999/86400; // 对应Max-Age的有效期 FCookieManager.CookieCollection.AddCookie(LCookie, 'https://www.google.com'); finally LCookie.Free; end; FHTTP.CookieManager := FCookieManager; end;模拟浏览器请求头
添加浏览器常用的请求头,降低被识别为爬虫的概率:FHTTP.Request.UserAgent := 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36'; FHTTP.Request.Accept := 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'; FHTTP.Request.AcceptLanguage := 'en-US,en;q=0.5';先确认Cookie状态再请求目标页面(可选)
先发送一次请求到Google主页,确保Cookie状态生效,再请求报价页面:// 先访问Google主页确认Cookie状态 FHTTP.Get('https://www.google.com/'); // 再请求目标报价页面 vSL.Text := FHTTP.Get(vURL);
注意事项
CONSENTCookie的值会因地区、语言、浏览器版本有所差异,必须从实际访问的浏览器中复制,不能直接使用示例值。- 若后续再次出现Cookie同意页,需重新获取最新的
CONSENT值更新代码。
内容的提问来源于stack exchange,提问作者Gabrielle Goldberg
相关产品推荐
相关产品推荐

