您好,登錄后才能下訂單哦!
小編給大家分享一下Python爬蟲中如何創建 beautifulsoup 對象,希望大家閱讀完這篇文章后大所收獲,下面讓我們一起去探討吧!
首先必須要導入 bs4 庫
from bs4 import BeautifulSoup
我們創建一個字符串,后面的例子我們便會用它來演示
html = """ <html><head><title>The Dormouse's story</title></head> <body> <p name="dromouse"><b>The Dormouse's story</b></p> <p>Once upon a time there were three little sisters; and their names were <a href="http://example.com/elsie" id="link1"><!-- Elsie --></a>, <a href="http://example.com/lacie" id="link2">Lacie</a> and <a href="http://example.com/tillie" id="link3">Tillie</a>; and they lived at the bottom of a well.</p> <p>...</p> """
創建 beautifulsoup 對象
soup = BeautifulSoup(html)
另外,我們還可以用本地 HTML 文件來創建對象,例如
soup = BeautifulSoup(open('index.html'))
上面這句代碼便是將本地 index.html 文件打開,用它來創建 soup 對象 下面我們來打印一下 soup 對象的內容,格式化輸出
print soup.prettify()
輸出結果:
<html> <head> <title> The Dormouse's story </title> </head> <body> <p name="dromouse"> <b> The Dormouse's story </b> </p> <p> Once upon a time there were three little sisters; and their names were <a href="http://example.com/elsie" id="link1"> <!-- Elsie --> </a> , <a href="http://example.com/lacie" id="link2"> Lacie </a> and <a href="http://example.com/tillie" id="link3"> Tillie </a> ; and they lived at the bottom of a well. </p> <p> ... </p> </body> </html>
看完了這篇文章,相信你對Python爬蟲中如何創建 beautifulsoup 對象有了一定的了解,想了解更多相關知識,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。