python - 从 HTML 字符串中删除所有 div 标签

标签 python regex

我正在尝试剥离所有 div。

输入:

<p>111</p>

<div class="1334">bla</div>

<p>333</p>

<p>333</p>

<div some unkown stuff>bla2</div>

期望的输出:

   <p>111</p>

    <p>333</p>

    <p>333</p>

我试过了,但没用:

release_content = re.sub("/<div>.*<\/div>/s", "", release_content)

最佳答案

Do not use regex for this problem .使用 html 解析器。这是一个使用 BeautifulSoup 的 python 解决方案:

from BeautifulSoup import BeautifulSoup

with open('Path/to/file', 'r') as content_file:
    content = content_file.read()

soup = BeautifulSoup(content)
[div.extract() for div in soup.findAll('div')]

with open('Path/to/file.modified', 'w') as output_file:
    output_file.write(str(soup))

关于python - 从 HTML 字符串中删除所有 div 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15796994/

相关文章:

ruby - bool 检查字符串是否与 ruby​​ 中的正则表达式匹配?

c# - .Net 正则表达式 : what is the word character\w?

Java RegEx 负向后视

javascript - 正则表达式排除包裹在特定 bbcode 标签中的匹配项

python - 连接两个不同的 mySQL 表的最佳方式——从 python 规划 django

python - 'WSGIRequest' 对象没有属性 'Post'

python - 可以使用比较来合并两个 Pandas 数据框吗?

php - 如果 install.php 存在,则访问 install.php,否则访问 index.php

python - 在 python 中迭代列以生成单独的图

python - 如何提取数组中的多个切片?