Learn Beautiful Soup(7) —— BeautifulSoup的輸出

BeautifulSoup不單單只是能夠查找,定位和修改文檔內容,一樣也能夠用一個好的 格式進行輸出顯示。BeautifulSoup能夠處理不一樣類型的輸出:javascript

  • 格式化的輸出
  • 非格式化的輸出

格式化輸出


BeautifulSoup中有內置的方法prettfy()來實現格式化輸出。好比:
from bs4 import BeautifulSoup

html_markup = """<p class="ecopyramid">
<ul id="producers">
<li class="producerlist">
<div class="name">plants</div>
<div class="number">100000</div>
</li>
<li class="producerlist">
<div class="name">algae</div>
Output in Beautiful Soup
<div class="number">100000</div>
</li>
</ul>"""
soup = BeautifulSoup(html_markup,"lxml")
print(soup.prettify())

輸出:



prettify()能夠用於BeautifulSoup對象也能夠用於任何標籤對象。好比:
producer_entry = soup.ul
print(producer_entry.prettify())


非格式化輸出


可使用str()和unicode()來進行非格式化輸出。
若是咱們對BeautifulSoup對象和標籤對象使用str()方法,那麼獲得的就是通常的字符串輸出樣式。
咱們也可使用前篇講到的encode()方法來指定編碼格式的輸出。
對BeautifulSoup對象或標籤對象使用decode()方法來獲得Unicode字符串。

BeautifulSoup中的輸出格式化


HTML實體編碼能夠放進HTML文檔中用來表示特別的字符和標識。這些標識不存在於鍵盤上,這些HTML實體編碼只是當瀏覽器打開後纔回看到效果。
在輸出方法中,只有這幾個HTML編碼有點例外。>和<和&三個符號。除此以外其餘的特別標識都是被轉換成Unicode編碼當建立BeautifulSoup對象時,且當使用Prettify()方法或者其餘方法輸出時,咱們只能獲得UTF-8格式的字符串。

html_markup = """<html>
<body>& &amp; ampersand
¢ &cent; cent
© &copy; copyright
÷ &divide; divide
> &gt; greater than
</body>
</html>

輸出:


能夠看到兩個沒有被轉換。BeautifulSoup自帶的輸出格式器來控制輸出。輸出格式器有如下幾種類型。
  • miimal
  • html
  • None
  • function
咱們能夠在輸出方法中傳遞上述輸出格式器參數,如prettify(),ncode(),decode()

miimal格式化


在這種格式化模式下,字符串被處理成一個有效的HTML代碼。這是默認的格式化輸出,此時輸出結果就和前面的同樣。不能轉換&amp;, &gt;和&lt;

Html格式化


這種格式化模式下,BeautifulSoup將會將Unicode字符轉換成HTML編碼形式。
print(soup.prettify(formatter="html"))html


輸出:



None格式化


這種狀況下,BeautifulSoup不會改變字符串。這會致使產生一個非法的HTML代碼。
print(soup.prettify(formatter=None))

輸出:



函數格式化


咱們能夠定義一個函數來處理字符串。好比去掉a字符。

def remove_chara(markup):
    return markup.replace("a","")
                 
soup = BeautifulSoup(html_markup,"lxml")
print(soup.prettify(formatter=remove_chara))

輸出:


注意,其中字符a被替換掉了,可是注意的是&amp;, &gt;,和&lt;也被轉換了。

使用get_text()


從網頁中獲得文本是常見的工做,BeautifulSoup提供了get_text()方法來達到目的。

若是咱們只想獲得BeautifulSoup對象的文本或標籤對象的文本內容,咱們可使用get_text()方法。好比:
html_markup = """<p class="ecopyramid">
<ul id="producers">
<li class="producerlist">
<div class="name">plants</div>
<div class="number">100000</div>
</li>
<li class="producerlist">
<div class="name">algae</div>
<div class="number">100000</div>
</li>
</ul>"""
soup = BeautifulSoup(html_markup,"lxml")
print(soup.get_text())

輸出:
plants
100000

algae
100000


get_text()方法返回BeautifulSoup對象或標籤對象中的文本內容,其爲一個Unicode字符串。可是get_text()有個問題是它一樣也會返回javascript代碼。

去掉javascript代碼的方法以下:
[x.extract() for x in soup_packtpage.find_all('script')]
這樣就會用處掉全部腳本元素。
相關文章
相關標籤/搜索