首页 > 解决方案 > 无法从 Google 搜索页面获取 CSS 类

问题描述

我使用BeautifulSoup来解析谷歌搜索,但我得到了空列表。我想用谷歌的“你的意思是吗?”来做一个拼写检查器。

import requests
from bs4 import BeautifulSoup
import urllib.parse


text = "i an you ate goode maan"
data = urllib.parse.quote_plus(text)

url = 'https://translate.google.com/?source=osdd#view=home&op=translate&sl=auto&tl=en&text='

rq = requests.get(url + data)

soup = BeautifulSoup(rq.content, 'html.parser')

words = soup.select('.tlid-spelling-correction spelling-correction gt-spell-correct-message')

print(words)

输出只是:[],但预期:“我和你是好人”(对不起这样一个糟糕的文本示例)

标签: pythonbeautifulsoupspell-checking

解决方案


首先,您要查找的元素是使用 javascript 加载的。由于 BeautifulSoup 不运行 js,因此目标元素不会加载到 DOM 中,因此查询选择器无法找到它们。尝试使用Selenium而不是 BeautifulSoup。

其次,CSS选择器应该是

.tlid-spelling-correction.spelling-correction.gt-spell-correct-message`. 

注意.每个类名前面的空格代替。

我已经使用 JS 查询选择器验证了它

在此处输入图像描述

您使用的选择器.tlid-spelling-correction spelling-correction gt-spell-correct-message正在寻找一个带有 class的元素,该元素gt-spell-correct-message位于一个带有 class 的元素内,而该元素spelling-correction本身位于另一个带有 class 的元素内tlid-spelling-correction

通过删除空格并在每个类名前放置一个点,选择器会查找包含所有上述三个类的元素。


推荐阅读