🐍Python🐍

  1. import re
  2. import ssl
  3. import html
  4. from urllib import parse
  5. import requests
  6. # 禁用警告InsecureRequestWarning
  7. from requests.packages.urllib3.exceptions import InsecureRequestWarning,InsecurePlatformWarning
  8. requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
  9. requests.packages.urllib3.disable_warnings(InsecurePlatformWarning)
  10. ssl._create_default_https_context = ssl._create_unverified_context
  11. GOOGLE_TRANSLATE_URL = 'http://translate.google.cn/m?q=%s&tl=%s&sl=%s'
  12. def translate(text, to_language="auto", text_language="auto"):
  13. text = parse.quote(text)
  14. url = GOOGLE_TRANSLATE_URL % (text,to_language,text_language)
  15. response = requests.get(url, verify=False)
  16. data = response.text
  17. expr = r'(?s)class="(?:t0|result-container)">(.*?)<'
  18. result = re.findall(expr, data)
  19. if (len(result) == 0):
  20. return ""
  21. return html.unescape(result[0])
  22. # 汉语转英语
  23. print(translate("谷歌翻译测试:汉语转英语", "en","zh-CN"))
  24. # 英语转汉语
  25. print(translate("Google Translate Test: Chinese to English", "zh-CN","en"))

问题

挂代理

  1. 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”

  1. 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')))

不挂代理

  1. 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”

弹出警告

  1. 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

禁用警告

  1. from requests.packages.urllib3.exceptions import InsecureRequestWarning,InsecurePlatformWarning
  2. requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
  3. requests.packages.urllib3.disable_warnings(InsecurePlatformWarning)

最后效果

image.png

浏览器安装了谷歌插件

可以考虑利用插件完成:
浏览器-插件 - 翻译本地文件