首页 > 解决方案 > 美丽的汤 - 我们如何在元素之前获得元素?

问题描述

如果我有一个如下的html,并且我使用漂亮的汤来解析它,我如何访问<head>元素之前的行。

<?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>

例如,访问 head 元素的标准方法是soup.head或者 body 是soup.body. 我认为这是因为 head 和 body 都是标准标签。

有没有办法访问之前的元素<head>

标签: pythonbeautifulsoup

解决方案


您可以通过选择 head 标签并遍历 previous_elements:

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 对象以供以后使用。


PS:请注意,我删除了<head>标签,因为<html>它是第一个previous_element. 我还格式化了非标记元素,因为它们的平面 str 格式不包括它们的前缀和后缀,使它们无法在 BS 对象中使用。


推荐阅读