python - Python 从 xhtml:link 抓取属性值
问题描述
我正在尝试从 href 属性中收集值。我以前做过这个,但似乎无法让它为“xhtml:link”工作。
我试过以下方法:
import xml.etree.ElementTree as ET
root = ET.parse('items.xml').getroot()
for type_tag in root.findall('xhtml:link'):
value = type_tag.get('href')
print(value)
和xml
<?xml version="1.0" encoding="UTF-8"?>
<url>
<loc>https://www.example.com</loc>
<xhtml:link rel="alternate" href="https://www.example.com"></xhtml:link>
<xhtml:link rel="alternate" href="https://www.example.com/"></xhtml:link>
<xhtml:link rel="alternate" href="https://www.example.com/"></xhtml:link>
<xhtml:link rel="alternate" href="https://www.example.com/"></xhtml:link>
<xhtml:link rel="alternate" href="https://www.example.com/"></xhtml:link>
<xhtml:link rel="alternate" href="https://www.example.com/"></xhtml:link>
</url>
我试图找到这背后的原因,但似乎找不到任何东西。任何建议都会非常感谢。
解决方案
xhtml
namespaces=
是一个命名空间,它需要选项findall()
第一:我必须添加xmlns:xhtml="your namespace"
才能运行它 - 可能你也有它。
我不得不在findall()
text = '''<?xml version="1.0" encoding="UTF-8"?>
<url xmlns:xhtml="your namespace">
<loc>https://www.example.com</loc>
<xhtml:link rel="alternate" href="https://www.example.com"></xhtml:link>
<xhtml:link rel="alternate" href="https://www.example.com/"></xhtml:link>
<xhtml:link rel="alternate" href="https://www.example.com/"></xhtml:link>
<xhtml:link rel="alternate" href="https://www.example.com/"></xhtml:link>
<xhtml:link rel="alternate" href="https://www.example.com/"></xhtml:link>
<xhtml:link rel="alternate" href="https://www.example.com/"></xhtml:link>
</url>'''
import xml.etree.ElementTree as ET
root = ET.fromstring(text)#.getroot()
for type_tag in root.findall('xhtml:link', namespaces={'xhtml':'your namespace'}):
value = type_tag.get('href')
print(value)
我不知道是否有忽略名称空间的功能。
推荐阅读
- python - 在python中使用列表作为函数参数
- ssl - 用于 TLS/SSL 和身份(签名)的证书之间有区别吗?
- angular - 使用 datefns 的当年星期的下拉列表
- python - 使用 Pymongo 到 MongoDB 实例的多个连接
- typescript - 是否可以动态地在泛型类型中使用 import()
- java - 在 Spring Boot 中编辑时选择多选中的项目
- dynamics-crm - 如何获取不在特定队列/团队中的用户?
- highcharts - Highcharts .Net(最新)YAxis.GridLineDashStyle Hashtable 不适用于客户端库
- perl - Perl - 如何从数组 M 维计算 N 个字节的 CRC16(使用 N
我需要计算从大小为 M 的二进制文件(一对 Kb,与我的范围不太相关)中提取的 N 字节(示例中为 5,为简单起见)的 CRC16。
printf "offset\tvalue\tcrc16\n"; #Read N bytes from file and copy in the container
- r - 子集,未按预期选择