小編給大家分享一下Python爬蟲中如何創(chuàng)建 beautifulsoup 對象,希望大家閱讀完這篇文章后大所收獲,下面讓我們一起去探討吧!

首先必須要導入 bs4 庫
from bs4 import BeautifulSoup
我們創(chuàng)建一個字符串,后面的例子我們便會用它來演示
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> """
創(chuàng)建 beautifulsoup 對象
soup = BeautifulSoup(html)
另外,我們還可以用本地 HTML 文件來創(chuàng)建對象,例如
soup = BeautifulSoup(open('index.html'))上面這句代碼便是將本地 index.html 文件打開,用它來創(chuàng)建 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爬蟲中如何創(chuàng)建 beautifulsoup 對象有了一定的了解,想了解更多相關知識,歡迎關注創(chuàng)新互聯行業(yè)資訊頻道,感謝各位的閱讀!
新聞標題:Python爬蟲中如何創(chuàng)建beautifulsoup對象-創(chuàng)新互聯
路徑分享:http://chinadenli.net/article44/dpgihe.html
成都網站建設公司_創(chuàng)新互聯,為您提供微信小程序、標簽優(yōu)化、網站收錄、App開發(fā)、服務器托管、面包屑導航
聲明:本網站發(fā)布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯