Beautifulsoup:当我尝试使用 Beautifulsoup4 访问 soup.head.next_sibling 值时换行

Beautifulsoup: Getting a new line when I tried to access the soup.head.next_sibling value with Beautifulsoup4

我正在尝试 BeautifulSoupDocs 中的示例,发现它表现得很奇怪。当我尝试访问 next_sibling 值时,出现了一个 '\n' 而不是 "body" 值。

html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>

<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>

<p class="story">...</p>
"""
from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc)
soup.head.next_sibling
u'\n'

我正在使用最新版本的 beautifulSoup4。即 4.3.2。请帮帮我。 提前致谢。

试试这个

soup.head.find_next_sibling()

soup.head.next_sibling.next_sibling

在HTML中BeautifulSoup"sees"有3个kinds of objects:

  • Tag
  • NavigableString
  • Comment

当你得到 .next_sibling 时,它 returns 你是当前对象之后的下一个对象,在你的例子中,它是一个文本节点 (NavigableString)。在文档中解释 here.

如果要在当前之后查找下一个 Tag,请使用 find_next_sibling(),或者指定标签名称:find_next_sibling("body").

您也可以使用 "next sibling" CSS Selector:

soup.select("head + *")