Beautiful Soup 简明教程

Beautiful Soup - find_next_siblings() Method

Method Description

find_next_siblings() 方法类似于 next_sibling 属性。它查找此 PageElement 同一级别内所有符合给定条件且在文档中后续出现的兄弟元素。

The find_next_siblings() method is similar to next_sibling property. It finds all siblings at the same level of this PageElement that match the given criteria and appear later in the document.

Syntax

find_fnext_siblings(name, attrs, string, limit, **kwargs)

Parameters

  1. name − A filter on tag name.

  2. attrs − A dictionary of filters on attribute values.

  3. string − The string to search for (rather than tag).

  4. limit − Stop looking after specified number of occurrences have been found.

  5. kwargs − A dictionary of filters on attribute values.

Return Type

find_next_siblings() 方法返回一个标签对象列表或一个 NavigableString 对象。

The find_next_siblings() method returns a list of Tag objects or a NavigableString objects.

Example 1

让我们为此目的使用以下 HTML 片段:

Let us use the following HTML snippet for this purpose −

<p>
   <b>
      Excellent
   </b>
   <i>
      Python
   </i>
   <u>
      Tutorial
   </u>
</p>

在下面的代码中,我们尝试查找所有的 <b> 标签的同级元素。在 HTML 字符串中有两个同级的标签用于抓取。

In the code below, we try to find all the siblings of <b> tag. There are two more tags at the same level in the HTML string used for scraping.

from bs4 import BeautifulSoup
soup = BeautifulSoup("<p><b>Excellent</b><i>Python</i><u>Tutorial</u></p>", 'html.parser')

tag1 = soup.find('b')
print ("next siblings:")
for tag in tag1.find_next_siblings():
    print (tag)

Output

find_next_siblings() 的 ResultSet 使用 for 循环进行迭代。

The ResultSet of find_next_siblings() is being iterated with the help of for loop.

next siblings:
<i>Python</i>
<u>Tutorial</u>

Example 2

如果在标签后没有同级元素,则此方法会返回一个空列表。

If there are no siblings to be found after a tag, this method returns an empty list.

from bs4 import BeautifulSoup

soup = BeautifulSoup("<p><b>Excellent</b><i>Python</i><u>Tutorial</u></p>", 'html.parser')

tag1 = soup.find('u')
print ("next siblings:")
print (tag1.find_next_siblings())

Output

next siblings:
[]