首页 > 解决方案 > XML解析-Python

问题描述

这是网址。我根本无法获得根返回;试图取回vessel_name 字段

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

标签: pythonxml

解决方案


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

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)

推荐阅读