如何优雅的抓取 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}")
相关推荐
摩羯座-185690305945 小时前
爬坑 10 年!京东店铺全量商品接口实战开发:从分页优化、SKU 关联到数据完整性闭环
linux·网络·数据库·windows·爬虫·python
蒋星熠8 小时前
反爬虫机制深度解析:从基础防御到高级对抗的完整技术实战
人工智能·pytorch·爬虫·python·深度学习·机器学习·计算机视觉
B站_计算机毕业设计之家9 小时前
python汽车数据分析可视化系统 爬虫 懂车帝 毕业设计 Django框架 vue框架 大数据✅
爬虫·python·数据分析·django·汽车·推荐算法·懂车帝
qq_4026056519 小时前
python爬虫(二) ---- JS动态渲染数据抓取
javascript·爬虫·python
浔川python社1 天前
《网络爬虫技术规范与应用指南系列》(xc—5)完
爬虫·python
深蓝电商API1 天前
爬虫的道德与法律边界:Robots 协议、版权与个人信息保护
爬虫
qq_402605651 天前
python爬虫(一) ---- 静态html数据抓取
爬虫·python·html
加油20192 天前
爬虫框架: selenium API使用介绍
爬虫·selenium·测试工具
好开心啊没烦恼2 天前
Python数据分析:使用爬虫从网页、社交媒体平台、论坛等公开资源提取中文和英文人名。
开发语言·爬虫·python·数据挖掘·数据分析
qq_402605652 天前
python爬虫(三) ---- 分页抓取数据
开发语言·爬虫·python