Reputation: 1897
Using google translation to translate a website content I find the error "No JSON object could be decoded". Here is the code:
import requests
from dragnet import extract_content
from googletrans import Translator
url = "https://bitcoin-bitcoin.themedia.jp/posts/4222377/"
r = requests.get(url)
content = extract_content(r.content)
translator = Translator()
text = translator.translate(content, dest='en').text
Output error:
Traceback (most recent call last):
File "test.py", line 9, in <module>
text = translator.translate(content, dest='en').text
File "/usr/local/lib/python2.7/dist-packages/googletrans/client.py", line 132, in translate
data = self._translate(text, dest, src)
File "/usr/local/lib/python2.7/dist-packages/googletrans/client.py", line 63, in _translate
data = utils.format_json(r.text)
File "/usr/local/lib/python2.7/dist-packages/googletrans/utils.py", line 62, in format_json
converted = legacy_format_json(original)
File "/usr/local/lib/python2.7/dist-packages/googletrans/utils.py", line 54, in legacy_format_json
converted = json.loads(text)
File "/usr/lib/python2.7/json/__init__.py", line 339, in loads
return _default_decoder.decode(s)
File "/usr/lib/python2.7/json/decoder.py", line 364, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python2.7/json/decoder.py", line 382, in raw_decode
raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded
Upvotes: 0
Views: 1360
Reputation: 1098
Based on the error, the content
variable you are passing is not in the expected format. Use print(type(content))
and print(content)
to understand what information are you passing and if it is the expected type.
The library you are using is not a Google official library. Find an official example here. Is true that you cannot translate a whole website and an equivalent solution is not implemented. You need to read the page and adequate it; or pre-process content
using dragnet, in your case.
Find below a Python Client Library for Translation API example:
# Imports the Google Cloud client library
from google.cloud import translate
# Instantiates a client
translate_client = translate.Client()
# The text to translate
text = u'Hello, world!'
# The target language
target = 'ru'
# Translates some text into Russian
translation = translate_client.translate(
text,
target_language=target)
print(u'Text: {}'.format(text))
print(u'Translation: {}'.format(translation['translatedText']))
Upvotes: 1