Python爬蟲(chóng)之Beautiful Soup用法

關(guān)于bs4,官方文檔的介紹已經(jīng)非常詳細(xì)了,傳送:Beautifulsoup 4官方文檔,這里我把它組織成自己已經(jīng)消化的筆記,你們最好看官方的,官方的全些可視化更強(qiáng)。本文從解釋器,DOM樹(shù)創(chuàng)建,遍歷DOM樹(shù),修改DOM樹(shù),Beautiful Soup3和4的區(qū)別,Soup結(jié)合Requests 這幾個(gè)主題整理。ps,其實(shí)如果掌握了javascript的DOM樹(shù)的話,會(huì)更好理解soup。



Beautiful Soup

將復(fù)雜HTML文檔轉(zhuǎn)換成一個(gè)復(fù)雜的樹(shù)形結(jié)構(gòu)DOM,每個(gè)節(jié)點(diǎn)都是Python對(duì)象,所有對(duì)象可以歸納為4種: Tag , NavigableString , BeautifulSoup , Comment .


A、DOM樹(shù)的解釋器


推薦使用lxml作為解析器,因?yàn)樾矢撸馕銎鞯暮锰幨强梢匀蒎e(cuò)比如沒(méi)有結(jié)束標(biāo)簽。


B、創(chuàng)建DOM樹(shù)的三種類型:

1)打開(kāi)本地文件with open("foo.html","r") as foo_file:soup_foo = BeautifulSoup(foo_file)

2)手動(dòng)創(chuàng)建soup = BeautifulSoup(“hello world”,編碼類型選填)

3)打開(kāi)外部文件url = "http://www.packtpub.com/books"??? page = urllib.urlopen(url)soup_packtpage = BeautifulSoup(page,'lxml')


C.DOM樹(shù)介紹:

節(jié)點(diǎn)【元素,屬性,內(nèi)容(string,NavigableString,contents,Comment】,還有節(jié)點(diǎn)的家庭【父節(jié)點(diǎn),同輩鄰接兄弟節(jié)點(diǎn),同輩往右鄰接所有兄弟節(jié)點(diǎn),同輩往左鄰接所有兄弟節(jié)點(diǎn),直接子節(jié)點(diǎn),所有子節(jié)點(diǎn)】

1)節(jié)點(diǎn)tag:類似javascript的元素-

訪問(wèn)元素:soup = BeautifulSoup(html_tag1,'lxml')tag1 = soup.a

訪問(wèn)元素的名字:tagname = tag1.name

訪問(wèn)元素的屬性:tag1['class']或tag1.attrs

修改元素的屬性訪問(wèn):? tag['class'] = 'verybold'賦予多個(gè)屬性rel_soup.a['rel'] = ['index', 'contents']
是否有元素的屬性:tag1.has_attr('class')
獲取所有屬性:比如獲取a所有標(biāo)簽的鏈接,for link in soup.find_all('a'): print(link.get('href'))

獲取元素的內(nèi)容:soup.p.string .如果tag包含了多個(gè)子節(jié)點(diǎn),tag就無(wú)法確定 .string 方法應(yīng)該調(diào)用哪個(gè)子節(jié)點(diǎn)的內(nèi)容, .string 的輸出結(jié)果是 None.? 如果tag中包含多個(gè)字符串 [2] ,可以使用 .strings 來(lái)循環(huán)獲取.for string in soup.strings: print(repr(string))

獲取元素的內(nèi)容含編碼過(guò)的:head_tag.contents,#[u'Hello', u' there']

獲取元素帶標(biāo)簽的內(nèi)容:head_tag.NavigableString,#<b>Hello there.</b>

獲取元素帶注釋的內(nèi)容Comment創(chuàng)建對(duì)象時(shí)用Comment,輸出對(duì)象時(shí)用soup.b.prettify()

獲取所有文字內(nèi)容:soup.get_text()

2)節(jié)點(diǎn)的家庭

訪問(wèn)直接子節(jié)點(diǎn):.children()? 和.contents()

.children() 不返回文本節(jié)點(diǎn),如果需要獲得包含文本和注釋節(jié)點(diǎn)在內(nèi)的所有子節(jié)點(diǎn),請(qǐng)使用 .contents()。

遍歷所有子節(jié)點(diǎn):.descendants

遍歷子節(jié)點(diǎn)的內(nèi)容:.strings.stripped_strings(去除空格或空行)

訪問(wèn)父節(jié)點(diǎn):.parent

遍歷所有父節(jié)點(diǎn):.parents

獲得匹配元素集合中所有元素的同輩元素:.next_siblings .previous_siblings

獲得匹配元素集合中的下或上一個(gè)同輩元素.next_element? .previous_element 屬性:

獲得匹配元素集合中的往后所有同輩或者往前所有元素:.next_elements? .previous_elements


D、遍歷DOM樹(shù)

可以通過(guò)方法或者css選擇器

方法:find_all( name , attrs , recursive , string, **kwargs )

參數(shù):支持可以使用的參數(shù)值包括 字符串 , 正則表達(dá)式 , 列表, True,自定義包含一個(gè)參數(shù)的方法Lambda表達(dá)式(這個(gè)我放在正則表達(dá)式那篇文章了)。

如支持字符串soup.find_all('b'),正則表達(dá)式soup.find_all(re.compile("^b")),列表soup.find_all(["a","b"]),True值如soup.find_all(True),自定義包含一個(gè)參數(shù)的方法如soup.find_all(has_class_but_no_id),而方法def has_class_but_no_id(tag): return tag.has_attr('class') and not tag.has_attr('id')。


name:是元素名,可以是一個(gè)元素find('head'),也可以是多個(gè)元素,多個(gè)元素可以用列表find(['a','b']),字典find({'head':True, 'body':True}),或者lambda表達(dá)式find(lambda name: if len(name) == 1) 搜索長(zhǎng)度為1的元素,或者正則表達(dá)式匹配結(jié)果find(re.compile('^p'))來(lái)表示,find(True) 搜索所有元素

attrs:是元素屬性。

搜索指定名字的屬性時(shí)可以使用的參數(shù)值包括 字符串 , 正則表達(dá)式 , 列表, True?

按照屬性值搜索tag:一個(gè)屬性如find(id='xxx') ,soup.find_all("a", class_="sister"),soup.find_all("a", attrs={"class": "sister"});也可以是多個(gè)屬性,比如正則表達(dá)式:find(attrs={id=re.compile('xxx'), p='xxx'})或者soup.find_all(class_=re.compile("itl")),或者true方法:find(attrs={id=True, algin=None}),或者列表方法find_all(attrs={"data-foo": "value"})。



recursive和limit參數(shù)

recursive=False表示只搜索直接兒子,否則搜索整個(gè)子樹(shù),默認(rèn)為True。當(dāng)使用findAll或者類似返回list的方法時(shí),limit屬性用于限制返回的數(shù)量,如findAll('p', limit=2): 返回首先找到的兩個(gè)tag.

soup.html.find_all("title", recursive=False)

string 參數(shù)

通過(guò) string參數(shù)可以搜搜文檔中的字符串內(nèi)容.與 name 參數(shù)的可選值一樣, text 參數(shù)接受 字符串 , 正則表達(dá)式 , 列表, 自定義方法,True.

soup.find_all(string="Elsie")#字符串

soup.find_all(string=["Tillie", "Elsie", "Lacie"]) )#列表

soup.find_all(string=re.compile("Dormouse"))#正則表達(dá)式

def is_the_only_string_within_a_tag(s): #方法

""Return True if this string is the only child of its parent tag.""

return (s == s.parent.string)

soup.find_all(string=is_the_only_string_within_a_tag)

關(guān)于Beautiful Soup樹(shù)的操作具體可以看官方文檔?


另外還有和find_all類似的方法:

find( name , attrs , recursive , text , **kwargs )

和find_all區(qū)別:返回第一個(gè)節(jié)點(diǎn)

find_parents()? find_parent()

find_next_siblings()? find_next_sibling()

find_previous_siblings()? find_previous_sibling()

find_all_next()? find_next()

find_all_previous() 和 find_previous()


除了find方法遍歷外,還有CSS選擇器

CSS選擇器:soup.select()

元素查找,比如元素名soup.select('a'),類名soup.select('.sister'),ID名.soupselect('#link1')或者soup.select("#link1,#link2"),組合查,比如soup.select('p #link1'),或者直接子元素選擇器soup.select("head > title"),所有子元素soup.select("body a"),篩選soup.select("p nth-of-type(3)"),soup.select("p > a:nth-of-type(2)")。

屬性查找soup.select('a[class="sister"]'),soup.select('p a[#link1 ~ .sister"),直接后面兄弟soup.select("#link1 + .sister"),soup.select('a[href*=".com/el"]')

查找到的元素的第一個(gè)soup.select_one(".sister")


E、修改DOM樹(shù)

修改tag的名稱和屬性:tag.name = "blockquote" tag['class'] = 'verybold'

修改tag的內(nèi)容:.string tag = soup.a?? tag.string = "New link text."

添加節(jié)點(diǎn)內(nèi)容:append()或者NavigableString構(gòu)造對(duì)象,new_string構(gòu)造comment注釋

append():soup.a.append("Bar"),輸出內(nèi)容時(shí)soup.a.contents,結(jié)果從"<a>Foo</a>變成<a>FooBar</a>"

NavigableString方法:new_string = NavigableString(" there") tag.append(new_string)

new_string構(gòu)造comment注釋:from bs4 import Comment new_comment = soup.new_string("Nice to see you.", Comment) tag.append(new_comment)


添加子節(jié)點(diǎn):new_tag(),第一個(gè)參數(shù)作為tag的name,是必填,其它參數(shù)選填

soup = BeautifulSoup("<b></b>") original_tag = soup.b

new_tag = soup.new_tag("a", ) original_tag.append(new_tag)

#<b><a ></b>


插入子節(jié)點(diǎn)或內(nèi)容:Tag.insert(指定位置索引,節(jié)點(diǎn)或內(nèi)容),Tag.insert_before(節(jié)點(diǎn)或內(nèi)容) 和 Tag.insert_after(節(jié)點(diǎn)或內(nèi)容)

tag = soup.p?

insert():tag.insert(1, "but did not")#從"<p>haha<a href='www.baidu.com'>i like <i>fish</i></a></p>"變成"<p>haha but did not <a href='www.baidu.com'></p>"

insert_before():如tag = soup.new_tag("i") tag.string = "Don't" soup.b.string.insert_before(tag)

insert_after():如soup.b.i.insert_after(soup.new_string(" ever "))


刪除當(dāng)前節(jié)點(diǎn)內(nèi)容:tag = soup.a ? ?? tag.clear()

刪除當(dāng)前節(jié)點(diǎn)并返回刪除后的內(nèi)容:tag=soup.i.extract(),注意這個(gè)tag是新創(chuàng)建的,和dom樹(shù)soup有區(qū)別。

刪除當(dāng)前tag并完全銷毀,不會(huì)創(chuàng)建新的:soup.i.decompose()
刪除當(dāng)前節(jié)點(diǎn)并替換新的節(jié)點(diǎn)或內(nèi)容:a_tag = soup.a new_tag = soup.new_tag("b") new_tag.string = "example.net" a_tag.i.replace_with(new_tag)

對(duì)指定節(jié)點(diǎn)進(jìn)行包裝,添加標(biāo)簽如div:soup.p.wrap(soup.new_tag("div"))

刪除指定節(jié)點(diǎn)的標(biāo)簽如a標(biāo)簽:tag.a.unwrap()


打印DOM樹(shù)或DOM樹(shù)的節(jié)點(diǎn):

含標(biāo)簽:soup.prettify() ,soup.p.prettify()? #<p>i will<p>

不含標(biāo)簽:unicode() 或 str() 方法:#i will

特殊字符如ldquo轉(zhuǎn)換成‘\’:soup = BeautifulSoup("“Dammit!” he said.") unicode(soup)

獲取本文內(nèi)容并以字符隔開(kāi):get_text(隔開(kāi)字符可選填,去除空白符開(kāi)關(guān)可選填),soup.get_text(),soup.get_text("|")如‘i like | fish’,soup.get_text("|", strip=True)


判斷節(jié)點(diǎn)內(nèi)容是否相同:first_b == second_b

判斷節(jié)點(diǎn)是否相同,即指向同一地址:first_b is second_b
判斷節(jié)點(diǎn)的類型是否是已知類型:isinstance(1, int)

復(fù)制節(jié)點(diǎn):p_copy = copy.copy(soup.p)




F、Python3和Python2版本的Beautiful Soup區(qū)別



G、Soup與Requests






附上可靠的網(wǎng)絡(luò)連接代碼

把這段代碼

from urllib.request import urlopen

from bs4 import BeautifulSoup

html = urlopen("http://www.pythonscraping.com/pages/page1.html")

bsObj = BeautifulSoup(html.read())

print(bsObj.h1)

改成以下代碼

from urllib.request import urlopen

from urllib.error import HTTPError

from bs4 import BeautifulSoup

??????? def getTitle(url):

?????? ? ? ? ? try:

???????????????????? html = urlopen(url)

??????? ? ? ? ? except HTTPError as e:

???????????????????? return None

?????????????? try:

???????????????????? bsObj = BeautifulSoup(html.read())

????????????????????? title = bsObj.body.h1

???????????? ?? except AttributeError as e:

????????????? ? ? ? ? return None

???????????? ?? return title

??????? title = getTitle("http://www.pythonscraping.com/pages/page1.html")

??????? if title == None:

??????????? print("Title could not be found")

??????? else:

???????????? print(title)




不過(guò),最終選擇了xpath

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容