You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python将HTML中指定class的div替换为对应标签名?

Solution Using BeautifulSoup in Python

To replace those <div> tags with custom tags based on their class names, we can use the BeautifulSoup library—it’s the go-to tool for parsing and modifying HTML in Python. Here’s a straightforward implementation:

Step 1: Install BeautifulSoup

First, make sure you have the library installed (if you don’t already):

pip install beautifulsoup4

Step 2: Python Code Implementation

This script will parse your input HTML, swap the target <div> tags with the appropriate custom tags, and discard the original class attribute (since it’s no longer needed):

from bs4 import BeautifulSoup

# Your input HTML content
input_html = """
<div class="title-title-1">hello</div>
<div class="text-body">i like you</div>
<div class="p">hehe</div>
"""

# Parse the HTML with BeautifulSoup
soup = BeautifulSoup(input_html, "html.parser")

# Iterate over every <div> element in the document
for div in soup.find_all("div"):
    # Grab the class name (we assume each div has exactly one class, as in your example)
    target_tag = div.get("class", [])[0]
    
    # Create a new tag using the class name as the tag type
    new_tag = soup.new_tag(target_tag)
    
    # Copy the content from the original div to the new tag
    new_tag.append(div.contents[0])
    
    # Replace the original div with our custom tag
    div.replace_with(new_tag)

# Output the modified HTML (use soup.prettify() for formatted, indented output)
print(str(soup))

Result

Running this code will produce exactly your desired output:

<title-title-1>hello</title-title-1>
<text-body>i like you</text-body>
<p>hehe</p>

Quick Notes

  • If some <div> tags have multiple classes, add a check to pick the specific class you want to use as the tag name (e.g., if "title-title-1" in div.get("class", [])).
  • Use soup.prettify() instead of str(soup) if you want nicely indented HTML for readability.

内容的提问来源于stack exchange,提问作者Taeho Bae

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:46:16