Beautiful Soup - smooth() 方法



方法描述

在调用了许多修改解析树的方法后,您最终可能会得到两个或多个 NavigableString 对象彼此相邻。smooth() 方法通过合并连续的字符串来平滑此元素的子元素。这使得在进行了许多修改树的操作后,美化后的输出看起来更自然。

语法

smooth()

参数

此方法没有参数。

返回类型

此方法在平滑后返回给定的标签。

示例 1

html ='''<html>
<head>
    <title>TutorislsPoint/title>
</head>
<body>
Some Text
    <div></div>
    <p></p>
    <div>Some more text</div>
    <b></b>
    <i></i> # COMMENT
</body>
</html>'''

from bs4 import BeautifulSoup

soup = BeautifulSoup(html, "html.parser")
soup.find('body').sm
for item in soup.find_all():
   if not item.get_text(strip=True):
      p = item.parent
      item.replace_with('')
      p.smooth()

print (soup.prettify())

输出

<html>
   <head>
      <title>
         TutorislsPoint/title>
      </title>
   </head>
   <body>
      Some Text
      <div>
         Some more text
      </div>
      # COMMENT
   </body>
</html>

示例 2

from bs4 import BeautifulSoup

soup = BeautifulSoup("<p>Hello</p>", 'html.parser')
soup.p.append(", World")

soup.smooth()
print (soup.p.contents)

print(soup.p.prettify())

输出

['Hello, World']
<p>
   Hello, World
</p>
广告

© . All rights reserved.