使用 BeautifulSoup 从另一个页面生成带有特定标签的 HTML 页面

Vil*_*ard 4 python beautifulsoup

我正在探索 BeautifulSoup 并旨在仅保留 HTML 文件中的特定标签以创建新文件。

我可以通过以下程序成功实现这一目标。但是,我相信可能有一种更合适、更自然的方法,无需手动附加字符串。

from bs4 import BeautifulSoup
#soup = BeautifulSoup(page.content, 'html.parser')

with open('P:/Test.html', 'r') as f:
    contents = f.read()
    soup= BeautifulSoup(contents, 'html.parser')

NewHTML = "<html><body>"
NewHTML+="\n"+str(soup.find('title'))
NewHTML+="\n"+str(soup.find('p', attrs={'class': 'm-b-0'}))
NewHTML+="\n"+str(soup.find('div', attrs={'id' :'right-col'}))
NewHTML+= "</body></html>"

with open("output1.html", "w") as file:
    file.write(NewHTML)
Run Code Online (Sandbox Code Playgroud)

And*_*ris 7

您可以拥有所需标签的列表,迭代它们,并使用 Beautiful Soup 的追加方法有选择地在新的 HTML 结构中包含相应的元素。

from bs4 import BeautifulSoup

with open('Test.html', 'r') as f:
    contents = f.read()
    soup = BeautifulSoup(contents, 'html.parser')

new_html = BeautifulSoup("<html><body></body></html>", 'html.parser')

tags_to_keep = ['title', {'p': {'class': 'm-b-0'}}, {'div': {'id': 'right-col'}}]

# Iterate through the tags to keep and append them to the new HTML
for tag in tags_to_keep:
    # If the tag is a string, find it in the original HTML
    # and append it to the new HTML
    if isinstance(tag, str):
        new_html.body.append(soup.find(tag))
    # If the tag is a dictionary, extract tag name and attributes,
    # then find them in the original HTML and append them to the new HTML
    elif isinstance(tag, dict):
        tag_name = list(tag.keys())[0]
        tag_attrs = tag[tag_name]
        new_html.body.append(soup.find(tag_name, attrs=tag_attrs))

with open("output1.html", "w") as file:
    file.write(str(new_html))
Run Code Online (Sandbox Code Playgroud)

假设您有一个如下所示的 HTML 文档(为了重现性而将其包含在内会很有帮助):

<!DOCTYPE html>
<head>
    <title>Test Page</title>
</head>
<body>
    <p class="m-b-0">Paragraph with class 'm-b-0'.</p>
    <div id="right-col">
        <p>Paragraph inside the 'right-col' div.</p>
    </div>
    <p>Paragraph outside the targeted tags.</p>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

结果output1.html将包含以下内容:

<html>
   <body>
      <title>Test Page</title>
      <p class="m-b-0">Paragraph with class 'm-b-0'.</p>
      <div id="right-col">
         <p>Paragraph inside the 'right-col' div.</p>
      </div>
   </body>
</html>
Run Code Online (Sandbox Code Playgroud)