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>
廣告