XML解析-Python

XML解析-Python,python,xml,Python,Xml,这里是URL。我根本找不到根回来;正在尝试获取船只名称字段 import urllib.request,urllib.parse import xml.etree.ElementTree as ET url='http://corpslocks.usace.army.mil/lpwb/xml.lockqueue?in_river=mI&in_lock=26' page=urllib.request.urlopen(url).read() tree = ET.ElementTree(

这里是URL。我根本找不到根回来;正在尝试获取船只名称字段

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

url='http://corpslocks.usace.army.mil/lpwb/xml.lockqueue?in_river=mI&in_lock=26'

page=urllib.request.urlopen(url).read()

tree = ET.ElementTree(page)
root=tree.getroot()
root.tag
root.attrib

主要问题是
urlopen()
以字节流的形式返回页面,需要在解析之前对其进行解码。解码后,您可以直接从字符串创建
元素树
。您可以使用该代码提取每个容器的名称:

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

url='http://corpslocks.usace.army.mil/lpwb/xml.lockqueue?in_river=mI&in_lock=26'

page=urllib.request.urlopen(url)
charset=page.info().get_content_charset() # check what charset is used
content=page.read().decode(charset) # decode reponse
tree = ET.fromstring(content)

for row in tree:
    print(row[0].text)

非常感谢你的帮助。用Python将Coursera翻译成“真实世界”对我来说很困难。你的帮助对我来说意义重大。不客气,如果答案是你所期望的,请投赞成票。