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

Python爬虫抓取Google同class属性元素仅返回第一条问题求解

问题解决方法

BeautifulSoup 中的 find() 方法仅会返回匹配规则的第一个元素,要获取所有相同class的元素,需改用 find_all() 方法,该方法会返回所有匹配元素组成的列表,遍历列表即可提取全部释义内容。

修改后的完整代码如下:

import requests
from bs4 import BeautifulSoup

search = input("Search: ")
URL = "https://www.google.co.in/search?q=" + search

headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36 Edg/89.0.774.57'
}

page = requests.get(URL, headers=headers)
soup = BeautifulSoup(page.content, 'html.parser') 
# 替换find为find_all,获取所有匹配指定class的元素
result_list = soup.find_all(class_="LTKOO sY7ric")

for index, item in enumerate(result_list, 1):
    # 非空判断避免找不到元素时报错
    if item:
        print(f"释义{index}:{item.get_text().strip()}")

补充说明:Google搜索页的class属性值是动态更新的,如果后续出现爬取不到结果的情况,可以重新审查页面元素更新对应的class值即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 13:39:02