【问题标题】:Beautiful soup- how can we get elements before the <head> element?美丽的汤——我们如何在 <head> 元素之前获取元素?
【发布时间】:2019-02-18 14:38:27
【问题描述】:

如果我有一个如下的html,并且我使用beautiful soup 来解析它,我如何访问&lt;head&gt; 元素之前的行。

<?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 都是标准标签。

有没有办法访问&lt;head&gt;之前的元素?

【问题讨论】:

  • 我建议在 BS 上使用 XML 解析器

标签: python beautifulsoup


【解决方案1】:

您可以通过选择 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)

在此过程之后,您将在prev_head 中将&lt;head&gt; 以上的所有代码作为字符串 .然后你可以BeautifulSoup(prev_head)得到一个BS对象供以后使用。


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

【讨论】:

    猜你喜欢
    • 2021-05-03
    • 1970-01-01
    • 2010-11-06
    • 2020-12-09
    • 2021-03-20
    • 2017-03-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多