You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

新手求助:用BeautifulSoup爬取谷歌搜索结果的两个问题

谷歌搜索结果爬取优化方案

实现两个核心需求:

  • 动态输入搜索关键词
  • 提取前3条结果的标题、链接、描述

修改后的完整代码

import requests
import bs4
from urllib.parse import urlparse, parse_qs

# 动态获取搜索关键词
text = input("请输入搜索关键词:")
# 对关键词进行URL编码,避免空格或特殊字符导致的请求错误
encoded_text = requests.utils.quote(text)
url = f'https://google.com/search?q={encoded_text}'

# 添加请求头模拟浏览器,避免被谷歌拦截
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36'
}

# 发送请求并解析页面
request_result = requests.get(url, headers=headers)
soup = bs4.BeautifulSoup(request_result.text, "html.parser")

# 定位每个搜索结果的容器(谷歌搜索结果通常用class为"g"的div包裹)
search_results = soup.select(".g")[:3]  # 只取前3条

# 遍历提取信息
for idx, result in enumerate(search_results, 1):
    # 提取标题
    title = result.find("h3").get_text(strip=True) if result.find("h3") else "无标题"
    
    # 提取链接:解析a标签的href参数,获取真实链接
    link_tag = result.find("a")
    if link_tag and "href" in link_tag.attrs:
        parsed_url = urlparse(link_tag["href"])
        real_link = parse_qs(parsed_url.query).get("q", ["无有效链接"])[0]
    else:
        real_link = "无有效链接"
    
    # 提取描述:谷歌搜索结果的描述通常在class为"VwiC3b"或"IsZvec"的div中
    description_tag = result.find("div", class_=["VwiC3b", "IsZvec"])
    description = description_tag.get_text(strip=True) if description_tag else "无描述"
    
    # 格式化输出
    print(f"第{idx}条结果:")
    print(f"标题:{title}")
    print(f"链接:{real_link}")
    print(f"描述:{description}")
    print("-" * 50)

关键改动说明

  1. 动态关键词输入:用input()函数替代固定字符串,运行时直接输入关键词即可。
  2. URL编码处理:用requests.utils.quote()对关键词编码,解决空格、特殊字符导致的请求失败问题。
  3. 请求头模拟:添加User-Agent伪装成浏览器,避免谷歌的反爬拦截。
  4. 结果容器定位:通过.g类选择器定位完整的搜索结果容器,确保能同时获取标题、链接、描述。
  5. 链接解析:谷歌搜索结果的a标签href是跳转链接,通过urlparse和parse_qs提取真实目标链接。
  6. 前3条结果限制:通过切片[:3]只保留前3条搜索结果。
  7. 异常处理:添加判断逻辑,避免部分结果缺失标题/链接/描述导致的报错。

内容的提问来源于stack exchange,提问作者Saravanan Ragavan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 17:30:05