python实现或爬取Google 翻译

python实现或爬取Google翻译,可以从两个方向考虑:爬虫和第三方库,爬虫就是使用requests或者selenium来实现,第三方库主要是官方提供的googletrans
原文
Mortality was increased after 2011, when intravitreal angiostatic treatment was introduced and referral practices altered.
Google翻译结果
2011 年之后死亡率增加,当时引入了玻璃体内血管抑制治疗并改变了转诊做法。
1.googletrans
googletrans 的基本用法可以参考文档连接:http://py-googletrans.rtfd.io/

from googletrans import Translator

translator = Translator()
data = translator.translate('Mortality was increased after 2011, when intravitreal angiostatic treatment was introduced and referral practices altered.', dest='zh-cn')
print(data)

运行之后会报错:httpcore._exceptions.ConnectTimeout: timed out

googletrans默认访问的是translate.google.com,国内无法直接访问,需要将service_urls换成translate.google.cn

from googletrans import Translator

translator = Translator(service_urls="translate.google.cn")
data = translator.translate('Mortality was increased after 2011, when intravitreal angiostatic treatment was introduced and referral practices altered.', dest='zh-cn')
print(data)

但是,依然会报错:httpcore._exceptions.ConnectError: [Errno 11001] getaddrinfo failed

总结而言,还是网络问题
网上有另一种库:google_trans_new,用法与googletrans类似

from google_trans_new import google_translator

translator = google_translator()
data = translator.translate('Mortality was increased after 2011, when intravitreal angiostatic treatment was introduced and referral practices altered.','zh-cn')
print(data)

结果:2011年以后,授予玻璃体内血管静脉治疗并改变了转诊实践时,死亡率增加。
与Google翻译,存在差异,不够专业
2. requests
通过网上的文章,之前用的是get请求,相对容易一点,但现在已经是post请求,参数在body里面,并且加密


一看这个,小编就放弃了使用爬虫,想要攻克google的反爬,需要大量时间
3.selenium
selenium 模拟浏览器操作,但是结果不够理想

from selenium import webdriver
import time

browser = webdriver.Chrome()

browser.get("https://translate.google.cn/")
time.sleep(2)
browser.find_element("class name", "er8xn").send_keys('Mortality was increased after 2011, when intravitreal angiostatic treatment was introduced and referral practices altered.')
time.sleep(2)
data = browser.find_element("class name", "P6w8m")
print(data.text)
browser.close()


综上:使用代码来翻译,没有直接使用网站翻译的结果专业

posted @ 2022-05-12 10:18  起司24  阅读(1394)  评论(0编辑  收藏  举报