如何使用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 ofstr(soup)if you want nicely indented HTML for readability.
内容的提问来源于stack exchange,提问作者Taeho Bae
相关产品推荐
相关产品推荐

