如何优雅的抓取 Google 搜索结果?

众所周知,通过 API 抓取搜索引擎结果是一件非常困难的事情,随着Web技术的发展,爬虫与反爬技术的对抗每时每刻都在进行。今天以 Python 抓取 Google 的搜索结果为例,分享一下自己的心得。

  1. 爬虫框架选择
  • requests: 笔者测试 requests 配合适合的 User-Agent + 代理池是可以成功
  • 如果策略升级还可以考虑 playwrightDrissionPageselenium (性能低,指纹容易被检测,快被时代淘汰了)
  1. 指定 Cookie
makefile 复制代码
cookies = {
    "CONSENT": "PENDING+987",
    "SOCS": "CAESHAgBEhIaAB",
}

这样设置的目的是跳过同意页面,避免抓取不到搜索结果页面。

  1. 指定 User-Agent

常见的 User-Agent 或者 fake-useragent 生成的 UA,效果都不是很好,或者返回失败,笔者找到了一个比较靠谱的 UA 方式,直接上代码:

python 复制代码
import random

def get_useragent():
    """
    用户代理字符串由以下部分组成:
    - Lynx 版本:Lynx/x.y.z,其中 x 为 2-3,y 为 8-9,z 为 0-2
    - libwww 版本:libwww-FM/x.y,其中 x 为 2-3,y 为 13-15
    - SSL-MM 版本:SSL-MM/x.y,其中 x 为 1-2,y 为 3-5
    - OpenSSL 版本:OpenSSL/x.y.z,其中 x 为 1-3,y 为 0-4,z 为 0-9
    """
    lynx_version = f"Lynx/{random.randint(2, 3)}.{random.randint(8, 9)}.{random.randint(0, 2)}"
    libwww_version = f"libwww-FM/{random.randint(2, 3)}.{random.randint(13, 15)}"
    ssl_mm_version = f"SSL-MM/{random.randint(1, 2)}.{random.randint(3, 5)}"
    openssl_version = f"OpenSSL/{random.randint(1, 3)}.{random.randint(0, 4)}.{random.randint(0, 9)}"
    return f"{lynx_version} {libwww_version} {ssl_mm_version} {openssl_version}"
  1. 海外代理池选择

代理池的使用也是重点,如果频繁请求的话,一个IP肯定是会被封禁的,就会出现429等错误,海外代理池大家可以自行去找,一般几美元/GB,一般都提供免费测试的。

  1. 设置语言环境和返回条数

可以通过 num 控制条数,指定语言环境为英文:&hl=en&gl=us,示例代码如下(笔者使用了 httpx 这个异步框架,requests 同步框架道理类似):

python 复制代码
from urllib.parse import quote
from httpx import AsyncClient

def get_useragent():
    """
    用户代理字符串由以下部分组成:
    - Lynx 版本:Lynx/x.y.z,其中 x 为 2-3,y 为 8-9,z 为 0-2
    - libwww 版本:libwww-FM/x.y,其中 x 为 2-3,y 为 13-15
    - SSL-MM 版本:SSL-MM/x.y,其中 x 为 1-2,y 为 3-5
    - OpenSSL 版本:OpenSSL/x.y.z,其中 x 为 1-3,y 为 0-4,z 为 0-9
    """
    lynx_version = f"Lynx/{random.randint(2, 3)}.{random.randint(8, 9)}.{random.randint(0, 2)}"
    libwww_version = f"libwww-FM/{random.randint(2, 3)}.{random.randint(13, 15)}"
    ssl_mm_version = f"SSL-MM/{random.randint(1, 2)}.{random.randint(3, 5)}"
    openssl_version = f"OpenSSL/{random.randint(1, 3)}.{random.randint(0, 4)}.{random.randint(0, 9)}"
    return f"{lynx_version} {libwww_version} {ssl_mm_version} {openssl_version}"
    
async def request_google(keyword, proxy, timeout=10):
    """
    请求 Google.com
    """
    encoded_keyword = quote(keyword)
    headers = {"User-Agent": get_useragent(), "Accept-Language": "en-US,en;q=0.9"}
    cookies = {
        "CONSENT": "PENDING+987",
        "SOCS": "CAESHAgBEhIaAB",
    }
    async with AsyncClient(proxy=proxy, timeout=timeout) as client:
        try:
            google_search_logger.info(f"Google search: {keyword}, proxy: {proxy}......")

            response = await client.get(
                f"https://www.google.com/search?q={encoded_keyword}&start=0&num=100&hl=en&gl=us",
                headers=headers,
                cookies=cookies,
            )
            google_search_logger.info(
                f"Google search: {keyword}, proxy: {proxy}, code: {response.status_code}"
            )
            if response.status_code != 200:
                return

            if "VIDEOS" not in response.text:
                with open("./error.html", "w") as f:
                    f.write(response.text)
                return

            return response.text
        except Exception as e:
            google_search_logger.error(f"Request google error: {e}")
相关推荐
火龙谷13 小时前
【爬虫】12306查票
爬虫
ζ小菜鸡14 小时前
我用Deepseek + 亮数据爬虫神器 1小时做出輿情分析器
爬虫·bright data
q5673152315 小时前
Go语言多线程爬虫与代理IP反爬
开发语言·爬虫·tcp/ip·golang
Go Dgg1 天前
Go语言实现豆瓣电影Top250爬虫
开发语言·爬虫·golang
攻城狮7号1 天前
Python爬虫第20节-使用 Selenium 爬取小米商城空调商品
开发语言·数据库·爬虫·python·selenium
奋斗者1号1 天前
浏览器自动化与网络爬虫实战:工具对比与选型指南
运维·爬虫·自动化
q567315232 天前
Node.js数据抓取技术实战示例
爬虫·python·scrapy·node.js
.生产的驴2 天前
SpringBoot 集成滑块验证码AJ-Captcha行为验证码 Redis分布式 接口限流 防爬虫
java·spring boot·redis·分布式·后端·爬虫·tomcat
来自星星的坤2 天前
Python 爬虫基础入门教程(超详细)
开发语言·爬虫·python
浩皓素2 天前
Python网络爬虫:从入门到实践
爬虫·python