您可以通过选择head标记并在前面的元素上循环:
from bs4 import BeautifulSoup
from w3lib.html import remove_tags
html= '<?xml version="1.0" encoding="utf-8" standalone="no"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head>'
soup= BeautifulSoup(html,"html.parser")
x= soup.head
while x.previous_element != None:
if not isinstance(x.previous_element, bs4.element.Tag):
p = x.previous_element.PREFIX + str(x.previous_element) +
x.previous_element.SUFFIX
prev_head = prev_head + p
else:
prev_head = str(x.previous_element) + prev_head
x = x.previous_element
prev_head = remove_tags(prev_head, which_ones= ("head",))
BeautifulSoup(prev_head)
<head>
在里面
prev_head
作为字符串
那你就可以了
BeautifulSoup(prev_head)
获取一个BS对象供以后使用。
注意,我删除了
<头部>
<html>
这是第一次
previous_element
. 我还格式化了非标记元素,因为它们的平面str格式不包含前缀和后缀,因此无法在BS对象中使用。