使用 BeautifulSoup 将 html 标签从一个 html 文件移动到另一个 html 文件

问题描述 投票:0回答:2

我有 2 个 HTML 文件,名为 A.htmlB.html。每个文件恰好有 1 个标签。我想用 BeautifulSoup 将 B.html 中的“pre”标签替换为 A.html 中的标签,但到目前为止我还没有找到任何解决方案,因为 A 有一些孩子。 我怎么做?谢谢!

A.html

<html>

<head>
  <style>
    <!-- Some CSS -->
  </style>

  <body>
    <pre>
 <b>Db</b>  <b>Eb</b>  <b>Ab</b>  <b>Gb</b>  <b>F</b>  <b>Bbm</b>  <b>Ebm</b> 
</pre>
  </body>

</html>

B.html

<html>

<head>
  <style>
    <!-- Some CSS -->
  </style>

  <body>
    <pre>
 
</pre>
  </body>

</html>

python html beautifulsoup
2个回答
0
投票
from bs4 import BeautifulSoup

首先让我们将文件保存在变量中:

htmlA = open("A.html", "r", encoding='utf-8').read()
htmlB = open("B.html", "r", encoding='utf-8').read()

现在我们将制作汤:

soupA = BeautifulSoup(htmlA, 'html.parser')
soupB = BeautifulSoup(htmlB, 'html.parser')

然后我们可以替换标签:

soupB.pre.replace_with(soupA.pre)

0
投票

嗨,我正在尝试做同样的事情。为什么这个脚本不起作用。有人可以帮忙吗!

© www.soinside.com 2019 - 2024. All rights reserved.