使用Python从页面中删除HTML标记内容

2024-09-28 01:28:53 发布

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

我有一个HTML文件,如下所示:

<!DOCTYPE HTML>
<html>

<head>

<title>Sezione microbiologia</title>
<link rel="stylesheet" src="./style.css">

</head>

<body>

<div id="content">
    <section id="main">
        <!-- SOME CONTENT... -->
        <h1>Prima diluizione</h1>
        <p>Some content including "prima diluizione"...</p>
        <h1>Seconda diluizione</h1>
        <p>Some content including "seconda diluizione"...</p>
        <h1>Terza diluizione</h1>
        <p>Some content including "terza diluizione"...</p>
    </section>

    <section id="second">
        <!-- SOME CONTENT... -->
    </section>

    <section id="third">
        <!-- SOME CONTENT... -->
    </section>

    <section id="footer">
        <!-- SOME CONTENT... -->
    </section>
</div>
</body>

</html>

问题描述:

我试图修改包含单词diluizione的标题<h1>,以将这个单词及其前缀替换为“Diluizione serial”。我尝试使用Python replace()来实现这一点,问题是<p>段落中的行都被截断了,而我只希望修改h1标记中的行。除此之外,我还没有找到一种自动去掉前缀的方法,即“Prima”、“Seconda”、“Terza”等

我尝试使用的代码

我现在想到了这个:

with open('./home.html') as file:
    text = file.read()


if "diluizione" in text:
    text = text.replace("diluizione", "diluizione seriale")

但这会产生:

<div id="content">
    <section id="main">
        <!-- SOME CONTENT... -->
        <h1>Prima diluizione seriale</h1>
        <p>Some content including "prima diluizione seriale"...</p>
        <h1>Seconda diluizione seriale</h1>
        <p>Some content including "seconda diluizione seriale"...</p>
        <h1>Terza diluizione seriale</h1>
        <p>Some content including "terza diluizione seriale"...</p>
    </section>

如您所见,即使是<p>标记中的文本也会受到影响,前缀的标题仍然存在

我的期望输出将是:

<div id="content">
    <section id="main">
        <!-- SOME CONTENT... -->
        <h1>Diluizione seriale</h1>
        <p>Some content including "prima diluizione"...</p>
        <h1>Diluizione seriale</h1>
        <p>Some content including "seconda diluizione"...</p>
        <h1>Diluizione seriale</h1>
        <p>Some content including "terza diluizione"...</p>
    </section>

非常感谢您的任何帮助或建议,提前表示感谢


Tags: textdividmainhtmlsectionsomecontent
2条回答

看看html.parser。与其尝试进行sting插值,不如将HTML解析为一个结构,然后从那里遍历它

您可以通过Pythonsre模块使用正则表达式来实现这一点。为了只过滤h1标记中的文本,可以使用positive lookbehindpositive lookahead策略

代码:

import re

with open("path/to/home.html") as file:
    text = file.read()

text = re.sub("(?<=<h1>)\w+ \w+(?=</h1>)", "Diluizione seriale", text)

print(text)

说明

正则表达式(?<=<h1>)\w+ \w+(?=</h1>)匹配包含在<h1></h1>之间的两个连续单词字符

输出

<!  SOME CONTENT...  >
<h1>Diluizione seriale</h1>
<p>Some content including "prima diluizione"...</p>
<h1>Diluizione seriale</h1>
<p>Some content including "seconda diluizione"...</p>
<h1>Diluizione seriale</h1>
<p>Some content including "terza diluizione"...</p>

相关问题 更多 >

    热门问题