如何在BeautifulSoup中定义自定义标签的属性?

时间:2017-04-11 20:49:00

标签: python html parsing beautifulsoup sgml

我有一个SGML文件混合了需要关闭的标签和不需要关闭的标签。 BeautifulSoup可以为HTML美化这个,但我的标签是自定义的,BeautifulSoup只是在文件的末尾关闭它们。这是来源:

from bs4 import BeautifulSoup
import requests

url = 'https://www.sec.gov/Archives/edgar/data/1122304/000119312515118890/0001193125-15-118890.hdr.sgml'
sgml = requests.get(url).text
soup = BeautifulSoup(sgml, 'html5lib')

这是file

<SEC-HEADER>0001193125-15-118890.hdr.sgml : 20150403
<ACCEPTANCE-DATETIME>20150403143902
<ACCESSION-NUMBER>0001193125-15-118890
<TYPE>DEF 14A
<PUBLIC-DOCUMENT-COUNT>37
<PERIOD>20150515
<FILING-DATE>20150403
<DATE-OF-FILING-DATE-CHANGE>20150403
<EFFECTIVENESS-DATE>20150403
<FILER>
<COMPANY-DATA>
<CONFORMED-NAME>AETNA INC /PA/
<CIK>0001122304
<ASSIGNED-SIC>6324
<IRS-NUMBER>232229683
<STATE-OF-INCORPORATION>PA
<FISCAL-YEAR-END>1231
</COMPANY-DATA>
...
</SEC-HEADER>

FILERCOMPANY-DATA需要结束标记而其他标记不需要。

如何告诉BeautifulSoup的解析器关闭行尾的某些标签?是否与BS如何处理brliadiv有关?

1 个答案:

答案 0 :(得分:0)

我没有找到如何在BeautifulSoup中控制树构建器。我刚用正则表达式关闭了open标签(由@ChristosPapoulas建议),最后得到了一个XML文件。

添加我在问题中的代码:

# Find all tags
all_tags = re.findall(
    r'<([^>/]+)>',
    sgml
)

# Find closed tags
closed_tags = re.findall(
    r'</([^>]+)>',
    sgml
)

# Deduce open tags
open_tags = [x for x in all_tags if x not in closed_tags]

# Closing open tags knowing that each of them takes just one line
sgml_xml = re.sub(
    r'(<({})>.*)'.format('|'.join(open_tags)),
    r'\1</\2>',
    sgml
)

仍然很好奇如何在树构建器中操作标记属性。