python - 无法从 Google 搜索页面获取 CSS 类

标签 python beautifulsoup spell-checking

我使用 BeautifulSoup用于解析 Google 搜索,但我得到的是空列表。我想使用 Google 的“您是说吗?”来制作拼写检查器。

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)

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

最佳答案

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

其次,CSS选择器应该是

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

注意 .而不是每个类名前面的空格。

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

enter image description here

您使用的选择器 .tlid-spelling-correction spelling-correction gt-spell-correct-message正在寻找类为 gt-spell-correct-message 的元素在类为 spelling-correction 的元素内它本身位于另一个类为 tlid-spelling-correction 的元素内.

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

关于python - 无法从 Google 搜索页面获取 CSS 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59116038/

相关文章:

ssl - 带有 SCAYT over HTTPS 的 CKEditor 给出安全警告

python - 根据条件删除字典中的条目

python - 如何在pyplot中自动标注最大值

python - 使用 Python 将多个 URL 中的不同变量抓取到一个 CSV 文件中

python - 抓取: cannot access information from web

python - 使用 Beautiful soup 的类属性

javascript - 使用 JQuery 或 JavaScript 覆盖 Chrome 浏览器拼写检查语言

python - 正确构建本地python3,支持bz2

python - 将 numpy 数组写入 lmdb

emacs - 如何使用 ispell 忽略 LaTeX 文件中的注释(如果可能,在 Emacs 中)