【问题标题】:Beautifulsoup: Getting a new line when I tried to access the soup.head.next_sibling value with Beautifulsoup4Beautifulsoup:当我尝试使用 Beautifulsoup4 访问 soup.head.next_sibling 值时获得新行
【发布时间】:2015-08-23 02:56:01
【问题描述】:

我正在尝试来自 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。请帮帮我。 提前致谢。

【问题讨论】:

    标签: python python-2.7 web web-scraping beautifulsoup


    【解决方案1】:

    BeautifulSoup 在 HTML 中“看到”了 3 个kinds of objects

    • Tag
    • NavigableString
    • Comment

    当您获得 .next_sibling 时,它会返回当前对象之后的下一个对象,在您的情况下,它是一个文本节点 (NavigableString)。在文档 here 中进行了解释。

    如果您想在当前找到下一个Tag,请使用find_next_sibling(),或者,指定标签名称:find_next_sibling("body")

    你也可以使用“下一个兄弟”CSS Selector

    soup.select("head + *")
    

    【讨论】:

    • 感谢 alecxe 的详细解释。
    【解决方案2】:

    试试这个

    soup.head.find_next_sibling()
    

    soup.head.next_sibling.next_sibling
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-03-17
      • 1970-01-01
      • 2015-04-29
      • 2019-08-14
      • 1970-01-01
      • 1970-01-01
      • 2019-07-18
      相关资源
      最近更新 更多