python︱HTML网页解析BeautifulSoup学习笔记
一、載入html頁(yè)面信息
一種是網(wǎng)站在線的網(wǎng)頁(yè)、一種是下載下來(lái)的靜態(tài)網(wǎng)頁(yè)。
1、在線網(wǎng)頁(yè)
參考《python用BeautifulSoup庫(kù)簡(jiǎn)單爬蟲入門+案例(爬取妹子圖)》中的載入內(nèi)容:
import requests from bs4 import BeautifulSoupheaders={'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.110 Safari/537.36','referer':"www.mmjpg.com" } all_url = 'http://www.mmjpg.com/' #'User-Agent':請(qǐng)求方式 #'referer':從哪個(gè)鏈接跳轉(zhuǎn)進(jìn)來(lái)的start_html = requests.get(all_url, headers=headers)#all_url:起始的地址,也就是訪問(wèn)的第一個(gè)頁(yè)面#headers:請(qǐng)求頭,告訴服務(wù)器是誰(shuí)來(lái)了。#requests.get:一個(gè)方法能獲取all_url的頁(yè)面內(nèi)容并且返回內(nèi)容。Soup = BeautifulSoup(start_html.text, 'lxml')#BeautifulSoup:解析頁(yè)面#lxml:解析器#start_html.text:頁(yè)面的內(nèi)容- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
2、本地的靜態(tài)頁(yè)面
url = ...\...\... soup = BeautifulSoup(open(url,'r',encoding = 'utf-8'))- 1
- 2
encoding 編碼這邊需要提前確認(rèn),直接open本地的html靜態(tài)html文件?
.
二、界面結(jié)構(gòu)簡(jiǎn)述
主要參考:Python爬蟲利器二之Beautiful Soup的用法?
Beautiful Soup將復(fù)雜HTML文檔轉(zhuǎn)換成一個(gè)復(fù)雜的樹(shù)形結(jié)構(gòu),每個(gè)節(jié)點(diǎn)都是Python對(duì)象,所有對(duì)象可以歸納為4種:
- Tag
- NavigableString
- BeautifulSoup
- Comment
以樣本為例:
html = """ <html><head><title>The Dormouse's story</title></head> <body> <p class="title" name="dromouse"><b>The Dormouse's story</b></p> <p class="story">Once upon a time there were three little sisters; and their names were <a href="http://example.com/elsie" class="sister" id="link1"><!-- Elsie --></a>, <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>; and they lived at the bottom of a well.</p> <p class="story">...</p> """- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
.
1、基本構(gòu)成——Tag
就是 HTML 中的一個(gè)個(gè)標(biāo)簽
<title>The Dormouse's story</title>- 1
以上整個(gè)叫做tag。通過(guò)標(biāo)簽名獲得里面的內(nèi)容的方式:
print soup.title #<title>The Dormouse's story</title>print soup.head #<head><title>The Dormouse's story</title></head>print soup.a #<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>print soup.p #<p class="title" name="dromouse"><b>The Dormouse's story</b></p>- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
其中title,head,p,a都是tag里面的標(biāo)簽名
兩個(gè)重要的屬性,是 name 和 attrs:
print soup.name print soup.head.name #[document] #head- 1
- 2
- 3
- 4
整個(gè)tag是一個(gè)document類型,?
其中標(biāo)簽名可以通過(guò)這樣的方式獲得(再如:soup.a.name)
- 1
- 2
p 標(biāo)簽的所有屬性打印輸出了出來(lái),得到的類型是一個(gè)字典。?
.
2、基本構(gòu)成——NavigableString
標(biāo)簽內(nèi)的文字,就是<title>The Dormouse's story</title>中的The Dormouse’s story
print soup.p.string #The Dormouse's story- 1
- 2
其中的文字相對(duì)來(lái)說(shuō)就是標(biāo)簽的注釋,利用 .string 來(lái)輸出它的內(nèi)容。其格式為:Comment 類型
if type(soup.a.string)==bs4.element.Comment:print soup.a.string- 1
- 2
延伸:strings 實(shí)踐
一個(gè)tag僅有一個(gè)子節(jié)點(diǎn),那么這個(gè)tag也可以使用 .string 方法?
如果tag中包含多個(gè)字符串 ,可以使用 .strings 來(lái)循環(huán)獲取
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
輸出結(jié)果
list(combine_soup.strings)['\n Example of p tag with class identical\n ','\n','\n Example of div tag with class identical\n ','\n']- 1
- 2
- 3
- 4
- 5
- 6
.
3、子節(jié)點(diǎn)——.contents .children
.contents,將tag的子節(jié)點(diǎn)以list列表的方式輸出。?
.children,返回的不是一個(gè) list,是一個(gè)list生成器,
- 1
- 2
- 1
- 2
- 3
4、子孫節(jié)點(diǎn)——.descendants
跟.children一樣輸出的是一個(gè)list生成器
for child in soup.descendants:print child #<p class="title" name="dromouse">The Dormouse's story<b>The Dormouse's story</b></p>- 1
- 2
- 3
可以看到與.children的區(qū)別,.descendants輸出的內(nèi)容比較多,不僅把.children的內(nèi)容輸出了 且加上了標(biāo)簽內(nèi)的文字:The Dormouse’s storyThe Dormouse’s story?
.
5、父節(jié)點(diǎn)—— .parent
通過(guò)元素的 .parents 屬性可以遞歸得到元素的所有父輩節(jié)點(diǎn),例如
content = soup.head.title.string for parent in content.parents:print parent.name #title #head #html #[document]- 1
- 2
- 3
- 4
- 5
- 6
- 7
.
6、兄弟節(jié)點(diǎn)—— .next_sibling .previous_sibling
print soup.p.next_sibling # 實(shí)際該處為空白 print soup.p.prev_sibling #None 沒(méi)有前一個(gè)兄弟節(jié)點(diǎn),返回 None print soup.p.next_sibling.next_sibling #<p class="story">Once upon a time there were three little sisters; and their names were #<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>, #<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a> and #<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>; #and they lived at the bottom of a well.</p> #下一個(gè)節(jié)點(diǎn)的下一個(gè)兄弟節(jié)點(diǎn)是我們可以看到的節(jié)點(diǎn)- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
.
7、前后節(jié)點(diǎn)——.next_element .previous_element
與 .next_sibling .previous_sibling 不同,它并不是針對(duì)于兄弟節(jié)點(diǎn),而是在所有節(jié)點(diǎn),不分層次
比如 head 節(jié)點(diǎn)為
<head><title>The Dormouse's story</title></head>- 1
那么它的下一個(gè)節(jié)點(diǎn)便是 title,它是不分層次關(guān)系的
print soup.head.next_element #<title>The Dormouse's story</title>- 1
- 2
.
三、搜索文檔樹(shù)
主要參考:Python爬蟲利器二之Beautiful Soup的用法
1、find_all( name , attrs , recursive , text , **kwargs )
搜索當(dāng)前tag的所有tag子節(jié)點(diǎn),并判斷是否符合過(guò)濾器的條件
(1)搜索節(jié)點(diǎn)
soup.find_all('b') # [<b>The Dormouse's story</b>]- 1
- 2
(2)正則表達(dá)——針對(duì)節(jié)點(diǎn)
import re for tag in soup.find_all(re.compile("^b")):print(tag.name) # body # b- 1
- 2
- 3
- 4
- 5
(3)傳列表
soup.find_all(["a", "b"]) # [<b>The Dormouse's story</b>, # <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>, # <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, # <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]- 1
- 2
- 3
- 4
- 5
(4)傳 True
相當(dāng)于遍歷節(jié)點(diǎn)有啥。
for tag in soup.find_all(True):print(tag.name) # html # head # title # body # p # b # p # a # a- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
(5)搜索文檔中的字符串內(nèi)容
soup.find_all(text="Elsie") # [u'Elsie']soup.find_all(text=["Tillie", "Elsie", "Lacie"]) # [u'Elsie', u'Lacie', u'Tillie']soup.find_all(text=re.compile("Dormouse")) [u"The Dormouse's story", u"The Dormouse's story"]- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
(6)href 參數(shù)——針對(duì)標(biāo)簽注釋
傳入 href 參數(shù),Beautiful Soup會(huì)搜索每個(gè)tag的”href”屬性:
soup.find_all(href=re.compile("elsie")) # [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>]- 1
- 2
(7)recursive 參數(shù)
檢索當(dāng)前tag的所有子孫節(jié)點(diǎn),如果只想搜索tag的直接子節(jié)點(diǎn)
soup.html.find_all("title") # [<title>The Dormouse's story</title>]soup.html.find_all("title", recursive=False) # []- 1
- 2
- 3
- 4
- 5
(8)加快效率——limit 參數(shù)
soup.find_all("a", limit=2) # [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>, # <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]- 1
- 2
- 3
延伸一:find實(shí)踐
有這么一段html源碼
combine_html = """<p class="identical">Example of p tag with class identical</p><div class="identical">Example of div tag with class identical<div>""" combine_soup = BeautifulSoup(combine_html,'lxml')# 搜索 combine_soup .find("div",class_="identical") combine_soup .select("div.identical")- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
結(jié)果輸出:
# 第一種輸出 <div class="identical">Example of div tag with class identical<div> </div></div> # 第二種輸出 [<div class="identical">Example of div tag with class identical<div></div></div>]- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
.
2、其他 find
find_parents() find_parent()- 1
find_all() 和 find() 只搜索當(dāng)前節(jié)點(diǎn)的所有子節(jié)點(diǎn),孫子節(jié)點(diǎn)等. find_parents() 和 find_parent() 用來(lái)搜索當(dāng)前節(jié)點(diǎn)的父輩節(jié)點(diǎn),搜索方法與普通tag的搜索方法相同,搜索文檔搜索文檔包含的內(nèi)容
find_next_siblings() find_next_sibling()- 1
這2個(gè)方法通過(guò) .next_siblings 屬性對(duì)當(dāng) tag 的所有后面解析的兄弟 tag 節(jié)點(diǎn)進(jìn)行迭代, find_next_siblings() 方法返回所有符合條件的后面的兄弟節(jié)點(diǎn),find_next_sibling() 只返回符合條件的后面的第一個(gè)tag節(jié)點(diǎn)
find_previous_siblings() find_previous_sibling()- 1
這2個(gè)方法通過(guò) .previous_siblings 屬性對(duì)當(dāng)前 tag 的前面解析的兄弟 tag 節(jié)點(diǎn)進(jìn)行迭代, find_previous_siblings() 方法返回所有符合條件的前面的兄弟節(jié)點(diǎn), find_previous_sibling() 方法返回第一個(gè)符合條件的前面的兄弟節(jié)點(diǎn)?
.
3、select——CSS選擇器
(1)通過(guò)標(biāo)簽名查找
案例一 print soup.select('title') #[<title>The Dormouse's story</title>]- 1
- 2
- 3
- 1
- 2
- 3
- 1
- 2
- 3
(2)通過(guò)類名查找
print soup.select('.sister') #[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]- 1
- 2
(3)id查找
print soup.select('#link1') #[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>]- 1
- 2
(4)屬性查找
查找時(shí)還可以加入屬性元素,屬性需要用中括號(hào)括起來(lái),注意屬性和標(biāo)簽屬于同一節(jié)點(diǎn),所以中間不能加空格,否則會(huì)無(wú)法匹配到。
print soup.select('a[class="sister"]') #[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]- 1
- 2
- 1
- 2
- 3
.
主要參考:
Beautiful Soup 4.4.0 文檔?
Python爬蟲利器二之Beautiful Soup的用法
延伸一:實(shí)踐
# 讀入內(nèi)容 contents = BeautifulSoup(open(url,'r',encoding = 'utf-8')).find_all("div",class_="caption col-md-12") #1.re庫(kù)用正則,提取標(biāo)簽中的html 內(nèi)容:<a target="001" class="002" href="../..//003.html">re.findall(r'\"(.*html)\"',str( content )) #2.re庫(kù)正則,在.find_all中使用 內(nèi)容:<a target="001" class="002" href="../..//003.html"> re.findall(r'\"(.*html)\"',str(content.find_all("a",class_="002")[0])) #3.提取標(biāo)簽下的文本內(nèi)容 內(nèi)容:content = <h4><a href="../../../img/56b311675fe3329a703cf9de.html">獨(dú)釣圖 可以看到該內(nèi)容前面有兩個(gè)<>標(biāo)簽,可以直接: content.find_all('a').strings[0]#4.相同標(biāo)簽,有類別屬性 內(nèi)容: <span class="a">text1<span class="b">text2 以上有兩個(gè)span相同的標(biāo)簽,可以通過(guò)class來(lái)輔助定位、查找: content.find_all('span',class_='pull-right').strings # 即為文本內(nèi)容#5.相同標(biāo)簽,無(wú)類別屬性 內(nèi)容: <span >text1<span >text2content.find_all('span').contents[0].strings 先生成一個(gè)列表,然后選中,再得到下面的文本材料# 6.奇怪的副標(biāo)題 內(nèi)容: <td width="285" valign="top">1764-1815</td> content.find_all('td',width="285", valign="top") 原文地址:http://blog.csdn.net/sinat_26917383/article/details/78204653總結(jié)
以上是生活随笔為你收集整理的python︱HTML网页解析BeautifulSoup学习笔记的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 根据”so劫持”过360加固详细分析
- 下一篇: python爬虫从入门到放弃(一)之初识