簡體   English   中英

AttributeError: 'str' object 沒有屬性 'request' - googletrans

[英]AttributeError: 'str' object has no attribute 'request' - googletrans

我正在嘗試使用我從pypi安裝的這個 google translate python library googletrans 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輸入代理信息的方式讓它不高興?

根據官方文檔,這似乎很混亂,但是這個 github 問題有解決方案

出於某種原因,文檔同時指定了字符串和 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")

您還可以設置一些環境變量。
對於 Windows:
cmd:

    set http_proxy=...
    set https_proxy=...

powershell:

    $env:http_proxy = ...; $env:https_proxy = ...

對於 Linux:

    export http_proxy=... https_proxy=...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM