使用python处理HTML标记

2024-10-01 15:36:22 发布

您现在位置:Python中文网/ 问答频道 /正文

在HTML文件中,我遇到了以下情况:

<span class="finereader"></span>

或者

^{pr2}$

我想把这些标签都去掉。第二个例子显示标签下可能有一个字母(或数字,但只有1)。不应该删除字母,只删除<span class="finereader">和下面的</span>。 有吗re.sub公司-哪个表达式可以做到这一点? 谢谢你的帮助。在


Tags: 文件re表达式html字母情况公司数字
2条回答

另一个使用BeautifulSoup的解决方案:

from bs4 import BeautifulSoup

soup = BeautifulSoup(open('htmlfile'))

for elem in soup.find_all('span', class_='finereader'):
    elem.replace_with(elem.string or '') 

print(soup.prettify())

您可能希望查看beautifulsoup,而不是为此任务使用正则表达式。在

然后您可以这样做:(在本例中使用一个字符串作为html文件)

from bs4 import BeautifulSoup

html_doc = """
<html>
<head>
<title>Sample</title>
</head>
<body>
<span class="dummy">a</span>
<span>b</span>
</body>
</html>
"""
soup = BeautifulSoup(html_doc)
for span in soup.find_all('span'):
    print(span.string)

# output:
# a
# b

相关问题 更多 >

    热门问题