Search code examples
pythongoogle-translategoogletrans

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


I am trying to use this google translate python library googletrans 3.0.0, which I installed from pypi.

I used this code to start with:

from googletrans import Translator

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

When I call the translator in the last line above, I got this error:

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'

Is it the way I am inputting the proxies information to the Translator that makes it unhappy?


Solution

  • This seems to be very confusing according to the official docs, but this github issue has a solution.

    For some reason the docs specify both strings and HTTPTransports but this has been clarified in the issue above.

    Basically:

    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")