我正在浏览Asheesh Laroia在PyCon 2010上的“Scrape the Web”演示文稿,我有一个关于特定代码行的问题,就是这一行:
title_element = parsed.getElementsByTagName('title')[0]
从函数:
def main(filename):
#Parse the file
parsed = xml.dom.minidom.parse(open(filename))
# Get title element
title_element = parsed.getElementsByTagName('title')[0]
# Print just the text underneath it
print title_element.firstChild.wholeText
我不知道'[0]'在该行末尾执行的是什么角色。“xml.dom.minidom.parse”是否将输入解析为列表?
此方法的(
getElementsByTagName
)文档说明:因为它提到“all子体”,那么是的,在all-likess中,它返回一个列表,这段代码只是索引以查看第一个元素。
查看这个方法的代码(在
Lib/xml/dom/minidom.py
中)-它确实返回一个列表。parse()
不返回列表;getElementsByTagName()
返回列表。您要求所有标记为<title>
的元素。大多数标记可以在文档中多次出现,因此当您请求这些元素时,将得到多个标记。返回它们的明显方式是作为列表或元组。在本例中,您只希望文档中有一个
<title>
标记,因此您只需获取列表中的第一个元素。相关问题 更多 >
编程相关推荐