BS4 python 添加标签错误

BS4 python add tag error

我正在尝试使用 BS4 在我的标签下的新行上添加一个标签,但我收到了一个错误

c:\PDW\Logfiles>bs.py
Traceback (most recent call last):
  File "C:\PDW\Logfiles\bs.py", line 10, in <module>
    title.insert_after(meta)
AttributeError: 'NoneType' object has no attribute 'insert_after'

这里是 python 代码

from bs4 import BeautifulSoup as Soup


soup = Soup(open("filter2.html"))

head = soup.find('HEAD')
meta = soup.new_tag('META')
meta['content'] = "text/html; charset=UTF-8"
meta['http-equiv'] = "Content-Type"
title.insert_after(meta)

print soup

和我的 HTML 文件

<HTML>
<HEAD>
<META NAME="robots" CONTENT="none">
<LINK REL="stylesheet" HREF="a.css" TYPE="text/css">
</HEAD>

我不确定哪里出了问题。我看过文档,一切似乎都是正确的。 有什么想法吗?

没有 TITLE 标签,它不需要一个,因为它的网页不会被很多人使用,只有我自己和家人

Beautiful Soup 会自动猜测无效的 HTML 标记并将其更改为有效的 HTML 标记。从而将 <HEAD> 更改为 <head>.

soup = Soup(open("filter2.html"))

head = soup.find('head')
title = soup.new_tag('title')
title.insert(1, "Some Title")
head.insert(1, title)

并且我建议您正确使用 HTML 标签以避免头痛。

解决了。再 google 和一杯咖啡后

现已完成

from bs4 import BeautifulSoup as Soup

soup = Soup(open("filter2.html"))

head = soup.find('head')
metatag = soup.new_tag('meta')
metatag.attrs['http-equiv'] = 'Content-Type'
metatag.attrs['content'] = 'text/html'
soup.head.append(metatag)

html = soup.prettify("utf-8")
with open("filter2.html", "wb") as file:
    file.write(html)