如何使用Python将ID标记添加到HTML标记 ?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (94)

我有一个包含特定标记的HTML文件,我需要以格式将ID号添加到每个标记中,例如id="rule_1"id="rule_1.1"id="rule_1.2"id="rule_1.2.1"等,当前的HTML是:

<div style="styles">
    <p class="classname">TEXT</p>
    <p class="classname">TEXT</p>
    <ul style="styles">
        <li>
            <p class="classname">TEXT</p>
        </li>
        <li>
            <p class="classname">TEXT</p>
        </li>
    </ul>
</div>

我需要HTML看起来像这样:

<div style="styles" id="rule_1">
    <p class="classname" id="rule_1.1">TEXT</p>
    <p class="classname" id="rule_1.2">TEXT</p>
    <ul style="styles" id="rule_1.3">
        <li id="rule_1.3.1">
            <p class="classname" id="rule_1.3.1.1">TEXT</p>
        </li>
        <li id="rule_1.3.2">
            <p class="classname" id="rule_1.3.2.1">TEXT</p>
        </li>
    </ul>
</div>

我可以手动编写这些文件,但我希望使用现有的HTML解析器库。是否可以使用BeautifulSoup或其他模块?

我试过这样的方法:

from bs4 import BeautifulSoup as html_parser

with open('outputs/HTML/{}.html'.format(deal), 'r') as read_file:
    html_source = read_file.read()

soup = html_parser(html_source, 'html.parser')
html_tags = soup.find_all(['div', 'p', 'span', 'ul', 'li'])

for each_tag in html_tags:
    each_tag.attrs['id'] = html_tags.index(each_tag)

with open('outputs/HTML/{}-id.html'.format(deal), 'w') as save_file:
    save_file.write(str(soup))

但这只是增加了id="1"id="2"等等

提问于
用户回答回答于

试试:

curr_tags = {}

for each_tag in html_tags:
    if html_tags.index(each_tag) == 0:
        each_tag.attrs['id'] = 'rule_1'
    else:
        parent_id = each_tag.parent.attrs['id']
        if parent_id in curr_tags.keys():
            curr_tags[parent_id] += 1
        else:
            curr_tags[parent_id] = 1
        each_tag.attrs['id'] = parent_id + '.{0}'.format(curr_tags[parent_id])

扫码关注云+社区

领取腾讯云代金券