首页 > 解决方案 > 无法找到谷歌搜索结果的文本

问题描述

我一直在尝试使用 BeautifulSoup 在google上查找每个搜索结果的文本。使用开发人员工具,我可以看到这是由<h3>带有class“LC20lb DKV0Md”的 a 表示的。

但是我似乎无法使用 BeautifulSoup 找到它。我究竟做错了什么?

import requests
from bs4 import BeautifulSoup

res = requests.get('http://google.com/search?q=world+news')
soup = BeautifulSoup(res.content, 'html.parser')
soup.find_all('h3', class_= 'LC201b DKV0Md')

标签: pythonweb-scrapingbeautifulsoup

解决方案


您不必按 搜索class,只需包含 a和 than的select所有内容即可:<h3><div>get_text()

import requests
from bs4 import BeautifulSoup

res = requests.get('http://google.com/search?q=world+news')
soup = BeautifulSoup(res.content, 'html.parser')

[x.get_text() for x in soup.select('h3 div')]

输出:

['World - BBC News',
 'BBC News World',
 'Latest news from around the world | The Guardian',
 'World - breaking news, videos and headlines - CNN',
 'CNN International - Breaking News, US News, World News and Video',
 'Welt-Nachrichten',
 'BBC World News (Fernsehsender)',
 'World News - Breaking international news and headlines | Sky News',
 'International News | Latest World News, Videos & Photos -ABC',
 'World News Headlines | Reuters',
 'World News - Hindustan Times',
 'World News | International Headlines - Breaking World - Global News']

推荐阅读