使用Googletrans时出现NoneType属性错误及降级后报错原因排查
Googletrans翻译报错原因分析
用户代码
from PIL import Image import pytesseract import googletrans from googletrans import Translator translator = Translator() pytesseract.pytesseract.tesseract_cmd = r"C:\\Program Files\\Tesseract-OCR\\tesseract.exe" with open("emre.txt", mode = "w+") as f: f.write(pytesseract.image_to_string("01-361.jpg")) s = open("emre.txt", "r") if s.mode == "r": ceviri = s.read() print(ceviri) result = translator.translate(ceviri, src= "en", dest="tr") with open("çeviri.txt", "w") as k: k.write(result.text)
第一次报错信息
Traceback (most recent call last): File "c:\Users\usr\amazon_py\çeviri.py", line 20, in <module> result = translator.translate(ceviri, src= "en", dest="tr") File "C:\Users\usr\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\googletrans\client.py", line 182, in translate data = self._translate(text, dest, src, kwargs) File "C:\Users\usr\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\googletrans\client.py", line 78, in _translate token = self.token_acquirer.do(text) File "C:\Users\usr\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\googletrans\gtoken.py", line 194, in do self._update() File "C:\Users\usr\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\googletrans\gtoken.py", line 62, in _update code = self.RE_TKK.search(r.text).group(1).replace('var ', '') AttributeError: 'NoneType' object has no attribute 'group'
降级版本后报错信息
File "c:\Users\usr\amazon_py\çeviri.py", line 20, in <module> emre = translator.translate(ceviri, src= "en", dest="tr") File "C:\Users\usr\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\googletrans\client.py", line 219, in translate parsed = json.loads(data[0][2]) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2288.0_x64__qbz5n2kfra8p0\lib\json\__init__.py", line 339, in loads raise TypeError(f'the JSON object must be str, bytes or bytearray, ' TypeError: the JSON object must be str, bytes or bytearray, not NoneType
报错原因分析
第一个错误(AttributeError)
Googletrans依赖网页版Google翻译的API,但Google会不定期更新网页的token生成逻辑。你使用的Googletrans版本中的token获取代码,无法在当前Google翻译网页中找到匹配的TKK参数,导致RE_TKK.search(r.text)返回None,调用group()方法时触发异常。
第二个错误(TypeError)
降级版本后,虽然token问题可能被部分修复,但仍存在以下可能:
- 网络请求失败:无法连接到Google翻译服务器,导致返回的数据为空(
None),json.loads无法解析空对象。 - 版本兼容性:降级后的Googletrans版本与你使用的Python 3.10存在兼容性问题,导致API请求逻辑异常,返回无效数据。
- OCR结果为空:如果
pytesseract.image_to_string识别图片后得到空字符串,传给翻译接口可能引发服务端返回异常,最终导致客户端拿到空数据。
内容的提问来源于stack exchange,提问作者Shaumne
相关产品推荐
相关产品推荐

