AttributeError: 'str' object has no attribute 'request' - googletrans

AttributeError: 'str' object has no attribute 'request' - googletrans

我正在尝试使用我从 pypi.

安装的 google 翻译 python 库 googletrans 3.0.0

我用这段代码开始:

from googletrans import Translator

proxies = {'http': 'http://myproxy.com:8080', 'https': 'http://myproxy.com:8080'}
translator = Translator(proxies=proxies)
translator.translate("colour")

当我调用上面最后一行的翻译器时,我得到了这个错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/alpha/miniconda3/lib/python3.9/site-packages/googletrans/client.py", line 182, in translate
    data = self._translate(text, dest, src, kwargs)
  File "/home/alpha/miniconda3/lib/python3.9/site-packages/googletrans/client.py", line 78, in _translate
    token = self.token_acquirer.do(text)
  File "/home/alpha/miniconda3/lib/python3.9/site-packages/googletrans/gtoken.py", line 194, in do
    self._update()
  File "/home/alpha/miniconda3/lib/python3.9/site-packages/googletrans/gtoken.py", line 54, in _update
    r = self.client.get(self.host)
  File "/home/alpha/miniconda3/lib/python3.9/site-packages/httpx/_client.py", line 755, in get
    return self.request(
  File "/home/alpha/miniconda3/lib/python3.9/site-packages/httpx/_client.py", line 600, in request
    return self.send(
  File "/home/alpha/miniconda3/lib/python3.9/site-packages/httpx/_client.py", line 620, in send
    response = self.send_handling_redirects(
  File "/home/alpha/miniconda3/lib/python3.9/site-packages/httpx/_client.py", line 647, in send_handling_redirects
    response = self.send_handling_auth(
  File "/home/alpha/miniconda3/lib/python3.9/site-packages/httpx/_client.py", line 684, in send_handling_auth
    response = self.send_single_request(request, timeout)
  File "/home/alpha/miniconda3/lib/python3.9/site-packages/httpx/_client.py", line 714, in send_single_request
    ) = transport.request(
AttributeError: 'str' object has no attribute 'request'

是不是我向 Translator 输入代理信息的方式让它不开心?

根据官方文档,这似乎很混乱,但是 this github issue has a solution

出于某种原因,文档同时指定了字符串和 HTTPTransports,但这已在上述问题中得到澄清。

基本上:

from httpcore import SyncHTTPProxy
from googletrans import Translator

http_proxy = SyncHTTPProxy((b'http', b'myproxy.com', 8080, b''))
proxies = {'http': http_proxy, 'https': http_proxy }

translator = Translator(proxies=proxies)
translator.translate("colour")