使用BeautifulSoup和Python进行HTML数据提取
我有一些HTML文本,里面有很多类似下面这种结构的内容:
<DOC>
<DOCNO> XXX-2222 </DOCNO>
<FILEID>AP-NR-02-12-88 2344EST</FILEID>
<HEAD>Reports Former Saigon Officials Released from Re-education Camp</HEAD>
<TEXT>
Lots of text here
</TEXT>
</DOC>
我需要做的是给每个结构加上索引,包括文档编号(DocNo)、标题(Headline)和文本(Text),这样我就可以后续进行分析(比如分词等)。
我在考虑使用BeautifulSoup这个工具,目前我写的代码是:
soup = BeautifulSoup (file("AP880212.html").read())
num = soup.findAll('docno')
但是这段代码只给我返回了以下格式的结果:
<docno> AP880212-0166 </docno>, <docno> AP880212-0167 </docno>, <docno> AP880212-0168 </docno>, <docno> AP880212-0169 </docno>, <docno> AP880212-0170 </docno>
我该如何提取出<>里面的数字呢?并把它们和标题和文本关联起来?
非常感谢,
Sasha
3 个回答
0
docnos = soup.findAll('docno')
for docno in docnos:
print docno.renderContents()
你也可以使用 renderContents()
来从标签中提取信息。
2
要获取标签中的内容:
docnos = soup.findAll('docno')
for docno in docnos:
print docno.contents[0]
1
像这样:
html = """<DOC>
<DOCNO> XXX-2222 </DOCNO>
<FILEID>AP-NR-02-12-88 2344EST</FILEID>
<HEAD>Reports Former Saigon Officials Released from Re-education Camp</HEAD>
<TEXT>
Lots of text here
</TEXT>
</DOC>
"""
import bs4
d = {}
soup = bs4.BeautifulSoup(html, features="xml")
docs = soup.findAll("DOC")
for doc in docs:
d[doc.DOCNO.getText()] = (doc.HEAD.getText(), doc.TEXT.getText())
print d
#{u' XXX-2222 ':
# (u'Reports Former Saigon Officials Released from Re-education Camp',
# u'\nLots of text here\n')}
注意,我在构造函数中传入了 features="xml"
。这是因为你的输入中有很多不标准的 HTML 标签。你可能还想在把文本保存到字典之前,使用 .strip()
方法去掉多余的空白,这样就不会对空白特别敏感了(当然,如果你是故意要这样,那就另当别论)。
更新:
如果同一个文件中有多个 DOC,而 features="xml"
限制只处理一个,那可能是因为 XML 解析器只期待有一个根元素。
比如,如果你把整个输入的 XML 包裹在一个单一的根元素中,它应该就能正常工作:
<XMLROOT>
<!-- Existing XML (e.g. list of DOC elements) -->
</XMLROOT>
所以你可以在文件中这样做,或者我建议你在把输入文本传给 beautifulsoup 之前,先在程序中处理一下:
root_element_name = "XMLROOT" # this can be anything
rooted_html = "<{0}>\n{1}\n</{0}>".format(root_element_name, html)
soup = bs4.BeautifulSoup(rooted_html, features="xml")