Andrew
Andrew

Reputation: 203

XML tag in Python

I am using Python to call the API and getting response.

below is the response.content

Image enter image description here

Here is the code:-

Here is the code:-

response = requests.get(url, params=payload)

if response.status_code == 200:
    print('Success!')
elif response.status_code == 404:
    print('Not Found.')

print(r.content)
tree=ET.fromstring(r.content)

How can I get the value of "PYTHON123.Python123" from the returned XML.

Upvotes: 0

Views: 31

Answers (1)

forkdbloke
forkdbloke

Reputation: 1565

Please make use of the following code to extract the string between the tags as shown below,

import re

str = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<string xmlns=\"http://www.PY.com/\">PYTHON123.PYTHON123</string>"
m = re.search('<string.*>(.*?)</string>', str);
print (m.group(1));

OUTPUT

PYTHON123.PYTHON123

While r.content gives you access to the raw bytes of the response payload, you will often want to convert them into a string using a character encoding such as UTF-8. The response will do that for you when you access using .text method:

response.text
'{"current_user_url":"https://api.github.com/user","current_user_authorizations_html_url":"https://github.com/settings/connections/applications{/client_id}","authorizations_url":"https://api.github.com/authorizations","code_search_url":"https://api.github.com/search/code?q={query}"}'

Upvotes: 1

Related Questions