🐍Python🐍
import re
import ssl
import html
from urllib import parse
import requests
# 禁用警告InsecureRequestWarning
from requests.packages.urllib3.exceptions import InsecureRequestWarning,InsecurePlatformWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
requests.packages.urllib3.disable_warnings(InsecurePlatformWarning)
ssl._create_default_https_context = ssl._create_unverified_context
GOOGLE_TRANSLATE_URL = 'http://translate.google.cn/m?q=%s&tl=%s&sl=%s'
def translate(text, to_language="auto", text_language="auto"):
text = parse.quote(text)
url = GOOGLE_TRANSLATE_URL % (text,to_language,text_language)
response = requests.get(url, verify=False)
data = response.text
expr = r'(?s)class="(?:t0|result-container)">(.*?)<'
result = re.findall(expr, data)
if (len(result) == 0):
return ""
return html.unescape(result[0])
# 汉语转英语
print(translate("谷歌翻译测试:汉语转英语", "en","zh-CN"))
# 英语转汉语
print(translate("Google Translate Test: Chinese to English", "zh-CN","en"))
问题
挂代理
requests.exceptions.SSLError: HTTPSConnectionPool(host='translate.google.cn', port=443): Max retries exceeded with url: /m?q=%E4%BD%A0%E5%90%83%E9%A5%AD%E4%BA%86%E4%B9%88?&tl=en&sl=zh-CN (Caused by SSLError(SSLEOFError(8, 'EOF occurred in violation of protocol (_ssl.c:997)')))
requests.get加了“, verify=False”
requests.exceptions.ProxyError: HTTPSConnectionPool(host='translate.google.cn', port=443): Max retries exceeded with url: /m?q=%E4%BD%A0%E5%90%83%E9%A5%AD%E4%BA%86%E4%B9%88?&tl=en&sl=zh-CN (Caused by ProxyError('Cannot connect to proxy.', FileNotFoundError(2, 'No such file or directory')))
不挂代理
requests.exceptions.ConnectTimeout: HTTPConnectionPool(host='translate.google.cn', port=80): Max retries exceeded with url: /m?q=%E4%BD%A0%E5%90%83%E9%A5%AD%E4%BA%86%E4%B9%88%3F&tl=en&sl=zh-CN (Caused by ConnectTimeoutError(<urllib3.connection.HTTPConnection object at 0x000001EAFA6CD9C0>, 'Connection to translate.google.cn timed out. (connect timeout=None)'))
解决
不挂代理+requests.get加参数“, verify=False”
弹出警告
urllib3\connectionpool.py:1043: InsecureRequestWarning: Unverified HTTPS request is being made to host 'translate.google.cn'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/1.26.x/advanced-usage.html#ssl-warnings
禁用警告
from requests.packages.urllib3.exceptions import InsecureRequestWarning,InsecurePlatformWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
requests.packages.urllib3.disable_warnings(InsecurePlatformWarning)
最后效果
浏览器安装了谷歌插件
可以考虑利用插件完成:
浏览器-插件 - 翻译本地文件