Beautifulsoup4:尝试访问soup.head.next_sibling值时出现换行符问题

8

我正在尝试BeautifulSoup文档中的一个例子,但发现它表现得很奇怪。当我尝试访问next_sibling值时,除了"body"之外,还出现了'\n'。

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。请帮助我解决问题。提前致谢。
2个回答

5

在HTML中,BeautifulSoup "看到"了3种对象:

  • Tag
  • NavigableString
  • Comment

当你使用.next_sibling时,它会返回当前节点之后的下一个节点,而在你的情况下,这是文本节点(NavigableString)。可在此处的文档中进行解释。

如果你想找到当前节点后面的下一个Tag,可以使用find_next_sibling()或指定标签名称:find_next_sibling("body")

你也可以使用“下一个兄弟元素”CSS选择器
soup.select("head + *")

感谢alecxe提供的详细解释。 - Rakesh Vidya Chandra

3

试试这个

soup.head.find_next_sibling()

或者
soup.head.next_sibling.next_sibling

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接