gpt4 book ai didi

python - 挑出 xml 文档中的标签?

转载 作者:太空宇宙 更新时间:2023-11-03 19:01:54 24 4
gpt4 key购买 nike

我有一个我认为相当简单的问题。

我从 gdata 检索了一个文件,该文件:https://gdata.youtube.com/feeds/api/videos/Ej4_G-E1cAM/comments

我正在尝试挑出

之间的文本
"< author >HERE< /author >" 

标签,因此我将得到仅包含用户名的输出。 python 是解决这个问题的最佳方法还是我应该使用其他语言?我从早上 8:00(4 小时)起就开始在谷歌上搜索,但还没有找到任何可以完成如此​​看似简单的任务的信息。

最诚挚的问候,- 米奇·鲍威尔

最佳答案

你那里有一个原子提要,所以我会使用feedparser处理这个问题:

import feedparser

result = feedparser.parse('https://gdata.youtube.com/feeds/api/videos/Ej4_G-E1cAM/comments')
for entry in result.entries:
print entry.author

打印:

FreebieFM
micromicros
FreebieFM
Sarah Grimstone
FreebieFM
# etc.

Feedparser 是一个外部库,但易于安装。如果您只需要使用标准库,您可以使用 ElementTree API ,但要解析 Atom 提要,您需要在解析器中包含 HTML 实体,并且必须处理命名空间(这不是 ElementTree 的强项):

from urllib2 import urlopen
from xml.etree import ElementTree

response = urlopen('https://gdata.youtube.com/feeds/api/videos/Ej4_G-E1cAM/comments')
tree = ElementTree.parse(response)

nsmap = {'a': 'http://www.w3.org/2005/Atom'}
for author in tree.findall('.//a:author/a:name', namespaces=nsmap):
print author.text

nsmap 字典让 ElementTreea: 前缀转换为这些元素的正确命名空间。

关于python - 挑出 xml 文档中的标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15816347/

24 4 0