簡體   English   中英

使用BeautifulSoup和Python提取Beautifulsoup HTML數據

[英]Beautifulsoup HTML data extraction with BeautifulSoup and Python

我有一些看起來像以下結構實例的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>

如何提取<>中的數字? 並將它們與標題和文字鏈接起來?

非常感謝你,

薩沙

要獲取標簽的內容:

docnos = soup.findAll('docno')
for docno in docnos:
    print docno.contents[0]

像這樣:

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")
docnos = soup.findAll('docno')
for docno in docnos:
       print docno.renderContents()

您還可以使用renderContents()從標記中提取信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM