我正在浏览 PyCon 2010 上 Asheesh Laroia 的“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”是否将输入解析为列表?
请您参考如下方法:
parse()不返回列表; getElementsByTagName()做。您要求所有带有 <title> 标签的元素.大多数标签可以在文档中出现多次,因此当您请求这些元素时,您会得到不止一个。返回它们的明显方式是作为列表或元组。
在这种情况下,您只需要一个 <title>标记在文档中,因此您只需获取列表中的第一个元素。
