I‘m trying to extract the xml (http://py4e-data.dr-chuck.net/comments_42.xml) which looks like:
<note>
<comments>
<comment>
<name>Romina</name>
<count>97</count>
</comment>
...
I need to count the number of tags and sum up the value in the tags, finally print them out.
I have tried to extract and parse the xml based on the sample code given but I also made some changes.
Please see my code:
import urllib.request, urllib.parse, urllib.error
import xml.etree.ElementTree as ET
import ssl
api_key = False
if api_key is False:
api_key = 42
serviceurl = 'http://py4e-data.dr-chuck.net/xml?'
# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
while True:
address = input('Enter location: ')
if len(address) < 1: break
url = serviceurl + urllib.parse.urlencode(address)
uh = urllib.request.urlopen(url, context=ctx)
data = uh.read()
print('Retrieved', len(data), 'characters')
tree = ET.fromstring(data)
count = 0
sum = 0
lst = tree.findall('comments/comment')
for item in lst:
value = int(item.find('count'.text))
count = count+1
sum = sum + value
print('Count:',count)
print('Sum:',sum)
I expect to get the count and sum of values, but the terminal said the "serviceurl" is invalid.