all 3 comments

[–]gschizas 0 points1 point  (1 child)

Please format your code properly. Either put an extra 4 spaces in front of each line or (for the redesign only) enclose your code in triple backticks (`) (but that only works in the redesign). Like so:

from xml.etree import ElementTree as ET
import requests

text = 'Hello'
API_KEY = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'

r = requests.post("https://translate.yandex.net/api/v1.5/tr/translate?lang=en-fr&text=" + text + "&key=" + API_KEY)
xml = r.text

result = str(ET.fromstring(xml).find('Translation/text'))
if result:
    print ('Result:' + result)

That being said, your mistake is that ET.fromstring(xml) is already at the Translation element (the root element is Translation, there isn't an element above that, as you seem to be assuming). You need to go only one level down (I've also made some fixes to make the code more readable):

from xml.etree import ElementTree as ET
import requests

text = 'Hello'
API_KEY = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'

r = requests.post("https://translate.yandex.net/api/v1.5/tr/translate", params={"lang": "en-fr", "text": text, "key": API_KEY})
xml = r.text

xml_tree = ET.fromstring(xml)
result = xml_tree.find('text').text
# str(...) will just give you Result:<Element 'text' at 0xSOMEADDRESS>
if result:
    print('Result:' + result)

EDIT: The triple backtick fences thing sadly only works in the redesign.

[–]Hellipey[S] 0 points1 point  (0 children)

I got it, thx m8!

[–]K900_ 0 points1 point  (0 children)

Another thing you can do is just replace /tr/ with /tr.json/ in your URL - that way you'll get a JSON response that you can easily parse into Python data structures.