Created
January 16, 2021 09:30
-
-
Save ayubmetah/feb8cd2daf9297f1338bcbccec029567 to your computer and use it in GitHub Desktop.
write a Python program to prompt for a URL, read the XML data from that URL using urllib and then parse and extract the comment counts from the XML data, compute the sum of the numbers in the file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Data file url: http://py4e-data.dr-chuck.net/comments_1070214.xml | |
#VERSION 1: | |
import urllib.request | |
import xml.etree.ElementTree as ET | |
import ssl | |
# Ignore SSL certificate errors | |
ctx = ssl.create_default_context() | |
ctx.check_hostname = False | |
ctx.verify_mode = ssl.CERT_NONE | |
url = input("Enter location: ") | |
response = urllib.request.urlopen(url) | |
print('Retrieving: ', url) | |
tree = ET.fromstring(response.read()) | |
total = sum([int(count.text) for count in tree.findall('comments/comment/count')]) | |
print("Sum: ", total) | |
#VERSION 2- My best | |
import urllib.request, urllib.parse, urllib.error | |
import xml.etree.ElementTree as ET | |
import ssl | |
ctx = ssl.create_default_context() | |
ctx.check_hostname = False | |
ctx.verify_mode = ssl.CERT_NONE | |
while True: | |
sum = 0 | |
address = input('Enter location: ') | |
if len(address) < 1: break | |
print('Retrieving', address) | |
uh = urllib.request.urlopen(address, context=ctx) | |
data = uh.read() | |
print('Retrieved', len(data), 'characters') | |
tree = ET.fromstring(data) | |
counts = tree.findall('.//count') | |
for i in counts : | |
count = int(i.text) | |
sum+= count | |
print('count:',len(counts)) | |
print('sum:',sum) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment