Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Parsing XML
#1
Hello,

I was trying to write a program that will 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.

However, I encountered an error as follow:
Traceback (most recent call last):
File "C:\py4e\File 12\12.3.py", line 6, in <module>
tree = ET.fromstring(url)

TypeError: a bytes-like object is required, not 'HTTPResponse'

Wondering what did I do wrong on line 6? Thank you!!

import urllib.request, urllib.parse, urllib.error
import xml.etree.ElementTree as ET

url=urllib.request.urlopen('http://py4e-data.dr-chuck.net/comments_305570.xml')

tree = ET.fromstring(url)

results = tree.findall('comments/comment')

count = 0
sum = 0

for line in results:
    x = int(line.find('count').text)
    count = count + 1
    sum = sum + x

print ("Count:",count)
print ("Sum:",sum)
Reply
#2
Add read() line 6.
tree = ET.fromstring(url.read())
Reply
#3
Thanks so much! it worked!
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020