您好,登錄后才能下訂單哦!
小編給大家分享一下Python爬蟲中如何創(chuàng)建 beautifulsoup 對(duì)象,希望大家閱讀完這篇文章后大所收獲,下面讓我們一起去探討吧!
首先必須要導(dǎo)入 bs4 庫(kù)
from bs4 import BeautifulSoup
我們創(chuàng)建一個(gè)字符串,后面的例子我們便會(huì)用它來(lái)演示
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 對(duì)象
soup = BeautifulSoup(html)
另外,我們還可以用本地 HTML 文件來(lái)創(chuàng)建對(duì)象,例如
soup = BeautifulSoup(open('index.html'))
上面這句代碼便是將本地 index.html 文件打開,用它來(lái)創(chuàng)建 soup 對(duì)象 下面我們來(lái)打印一下 soup 對(duì)象的內(nèi)容,格式化輸出
print soup.prettify()
輸出結(jié)果:
<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>
看完了這篇文章,相信你對(duì)Python爬蟲中如何創(chuàng)建 beautifulsoup 對(duì)象有了一定的了解,想了解更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。