【问题标题】:Scraping Google Translate Python爬取谷歌翻译 Python
【发布时间】:2019-01-12 14:43:51
【问题描述】:

作为对我自己的挑战,我正在尝试从谷歌翻译中抓取翻译。我通过浏览器模拟请求下载了 html 文件,然后使用 beautifulSoupe 4 我尝试在 html 代码中查找翻译。问题是,虽然我可以在 Chrome WebDev 模式下找到我想要的东西,但我无法在 Python 中或使用其他程序(如 noteblock)来做这样的事情。这是我的代码:

while Translating==True:
text=input(("Values to translate:"))
#CREATING URL TO SCRAPE
translator_url_with_translation_embebed= translator_url+ EncodeTexttoURL(text)
#REQUESTING PAGE WITH FAKE HEADERS (avoiding no browser detection)
url = translator_url_with_translation_embebed
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}
response= requests.get(url, headers=headers)
print(response.content)
#ANALISING RESPONSE FOR FURTHER USE
sopa = BeautifulSoup(response.content)

translation_location=sopa.find_all('span', {'class' : 'tlid-translation translation'})
print("TRANSLATED LOCATIOON")
print(translation_location

` translation_location 输出一个空列表。

在 html 代码中显示翻译的浏览器开发模式:

我怎样才能找到它们?其他地方有翻译吗?谷歌是否发送了他们网站的修改版本来愚弄我?!

感谢您的帮助

【问题讨论】:

标签: python-3.x web-scraping beautifulsoup


【解决方案1】:

翻译后的单词来自 XMLHttpRequest,beautifulsoup 无法处理。复制请求(复杂)或使用 Selenium。但我认为使用googletrans 库更容易。

$ pip install googletrans

然后是你的代码

from googletrans import Translator

while Translating==True:
    translator = Translator()
    text=input(("Values to translate:"))
    translation = translator.translate(text, dest='en')
    print(translation.text)

【讨论】:

  • 但是如果我只想在开发模式下看到 HTML 代码怎么办?我怎么得到它?这应该适用于 BeautifulSoup!有趣的是,BS 从来没有真正给出过错误,但是自从它是 XMLHttpRequest 以来的任何方式都意味着我们获得的信息是重要的,但据我了解,真正采用相同格式的 .html,对吧?
  • 你不能,因为它是由 Javascript 和 BS 生成的,不能执行 JS 代码。要获取内容,在开发工具中切换到网络选项卡并观看以 translate.google.com/translate_a/single... 开头的 URL 并复制此请求
  • 哦,我明白了.. URL 以非线性方式变化,因此为了复制它,我们需要构建 Web 浏览器的一些功能...... Thxx 我会看看Selenium 并设法解决这个问题。谢谢帮助
  • Selenium 使用更多 CPU 资源,我将使用该库代替或学习它们的工作原理。
  • Google API 的翻译结果似乎与从网站“translate.google.com”直接查询的结果不同。如何解决问题?网站翻译似乎更准确。
【解决方案2】:
py -m pip install "googletrans"
py -m pip install googletrans==4.0.0rc1
py -m pip install beautifulsoup4


from bs4 import BeautifulSoup
from bs4.formatter import HTMLFormatter
from googletrans import Translator
import requests

translator = Translator()

在此处查看完整的 Python 代码:

https://neculaifantanaru.com/en/python-code-text-google-translate-website-translation-beautifulsoup-library.html

或在这里:

https://neculaifantanaru.com/en/example-google-translate-api-key-python-code-beautifulsoup.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-26
    相关资源
    最近更新 更多