python - 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
解决方案
主要问题是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)
推荐阅读
- elasticsearch - 使用 fluentd 不会将日志发送到 elasticsearch。日志写在一行中
- tensorflow - 有没有办法获得 hdf5 格式的高效网络预训练权重?
- python - Graphen Django:批处理请求应该收到一个列表,但收到 {'query': XXX}
- c++ - 检查多个平台上的进程?
- javascript - 为什么“onpaste”在 Visual Studio 2019 中未被识别为有效的 javascript 事件?
- kivy - 使用 kivy 模块不透明的画布中的图像
- algorithm - 用于在 1,000,000,000 个元素中搜索键的算法,其中键位于前 n 个索引中,而不事先指定 n
- python - 为什么我得到 FileNotFoundError:[WinError 2] 系统找不到指定的文件:错误
- ruby-on-rails - 在每个循环中获取 has_many 关联记录的最快方法
- environment-variables - 将环境变量传递给 Visual Studio 2019 中的测试