Beautiful Soup 简明教程
Beautiful Soup - NavigableString() Method
Method Description
bs4 包中的 NavigableString() 方法是 NavigableString 类的构造方法。NavigableString 表示解析文档的最内层子元素。此方法将常规 Python 字符串转换为 NavigableString。相反,内置的 str() 方法将 NavigableString 对象转换为 Unicode 字符串。
The NavigableString() method in bs4 package is the constructor method for NavigableString class. A NavigableString represents the innermost child element of a parsed document. This method casts a regular Python string to a NavigableString. Conversely, the built-in str() method coverts NavigableString object to a Unicode string.
Return Value
NavigableString() 方法返回一个 NavigableString 对象。
The NavigableString() method returns a NavigableString object.
Example 1
在下面的代码中,HTML 字符串包含一个空的 <b> 标签。我们向其中添加一个 NavigableString 对象。
In the code below, the HTML string contains an empty <b> tag. We add a NavigableString object in it.
html = """
<p><b></b></p>
"""
from bs4 import BeautifulSoup, NavigableString
soup = BeautifulSoup(html, 'html.parser')
navstr = NavigableString("Hello World")
soup.b.append(navstr)
print (soup)
Example 2
在这个示例中,我们看到两个 NavigableString 对象被追加到一个空的 <b> 标签。标签响应 strings 属性而不是 string 属性。它是一种 NavigableString 对象的生成器。
In this example, we see that two NavigableString objects are appended to an empty <b> tag. The tag responds to strings property instead of string property. It is a generator of NavigableString objects.
html = """
<p><b></b></p>
"""
from bs4 import BeautifulSoup, NavigableString
soup = BeautifulSoup(html, 'html.parser')
navstr = NavigableString("Hello")
soup.b.append(navstr)
navstr = NavigableString("World")
soup.b.append(navstr)
for s in soup.b.strings:
print (s, type(s))
Example 3
如果我们访问了 <b> 标签对象的 stripped_strings 属性而不是 strings 属性,则会得到 Unicode 字符串的生成器,即 str 对象。
Instead of strings property, if we access the stripped_strings property of <b> tag object, we get a generator of Unicode strings i.e. str objects.
html = """
<p><b></b></p>
"""
from bs4 import BeautifulSoup, NavigableString
soup = BeautifulSoup(html, 'html.parser')
navstr = NavigableString("Hello")
soup.b.append(navstr)
navstr = NavigableString("World")
soup.b.append(navstr)
for s in soup.b.stripped_strings:
print (s, type(s))