使用Python Requests调用谷歌搜索遇Cookie页,AWS虚拟机如何绕过?
原因分析
谷歌会根据请求的IP地址、用户代理(User-Agent)、会话信息等判断访问者是否需要展示Cookie同意页。AWS云实例的IP属于数据中心IP,容易被识别为非普通用户访问,加上requests默认的请求头过于直白,导致触发Cookie验证。
解决方案
1. 模拟真实浏览器请求头
替换requests默认的User-Agent为主流浏览器的标识,同时补充必要的请求头,让请求更接近真实用户访问:
import requests headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36', 'Accept-Language': 'en-US,en;q=0.9', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8' } response = requests.get("https://www.google.com/search?q=usd+in+myr", headers=headers) print(response.text)
2. 携带已验证的Cookie
如果模拟请求头无效,可以在AWS虚拟机的浏览器中手动访问谷歌搜索并同意Cookie,然后从浏览器开发者工具(F12)的Application > Cookies中复制NID、1P_JAR等关键Cookie值,添加到请求中:
import requests headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36', 'Accept-Language': 'en-US,en;q=0.9' } cookies = { 'NID': '替换为你的NID Cookie值', '1P_JAR': '替换为你的1P_JAR Cookie值' } response = requests.get("https://www.google.com/search?q=usd+in+myr", headers=headers, cookies=cookies) print(response.text)
3. 使用Session自动处理Cookie同意
通过requests.Session()维持会话,先提交Cookie同意请求,再获取搜索结果:
import requests session = requests.Session() session.headers.update({ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36', 'Accept-Language': 'en-US,en;q=0.9' }) # 先访问搜索页触发Cookie同意流程 initial_res = session.get("https://www.google.com/search?q=usd+in+myr") # 提交Cookie同意表单(参数需匹配当前页面的实际值,可从页面源码中提取) consent_payload = { 'gl': 'US', 'hl': 'en', 'continue': 'https://www.google.com/search?q=usd+in+myr', 'set_eom': 'true', 'set_sc': 'true' } session.post("https://consent.google.com/save", data=consent_payload) # 再次请求搜索页获取结果 final_res = session.get("https://www.google.com/search?q=usd+in+myr") print(final_res.text)
注意事项
- 谷歌的反爬机制会动态更新,上述方法可能随时间失效,需根据实际页面调整参数。
- 避免高频请求,防止IP被封禁;必要时可搭配代理IP使用。
- 根据AWS实例的地域调整
gl(地区代码)和hl(语言代码)参数,比如新加坡实例可设gl=SG、hl=en-SG。
内容的提问来源于stack exchange,提问作者wil
相关产品推荐
相关产品推荐

