python︱HTML网页解析BeautifulSoup学习笔记
一、載入html頁面信息
一種是網站在線的網頁、一種是下載下來的靜態網頁。
1、在線網頁
參考《python用BeautifulSoup庫簡單爬蟲入門+案例(爬取妹子圖)》中的載入內容:
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':請求方式 #'referer':從哪個鏈接跳轉進來的start_html = requests.get(all_url, headers=headers)#all_url:起始的地址,也就是訪問的第一個頁面#headers:請求頭,告訴服務器是誰來了。#requests.get:一個方法能獲取all_url的頁面內容并且返回內容。Soup = BeautifulSoup(start_html.text, 'lxml')#BeautifulSoup:解析頁面#lxml:解析器#start_html.text:頁面的內容- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
2、本地的靜態頁面
url = ...\...\... soup = BeautifulSoup(open(url,'r',encoding = 'utf-8'))- 1
- 2
encoding 編碼這邊需要提前確認,直接open本地的html靜態html文件?
.
二、界面結構簡述
主要參考:Python爬蟲利器二之Beautiful Soup的用法?
Beautiful Soup將復雜HTML文檔轉換成一個復雜的樹形結構,每個節點都是Python對象,所有對象可以歸納為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、基本構成——Tag
就是 HTML 中的一個個標簽
<title>The Dormouse's story</title>- 1
以上整個叫做tag。通過標簽名獲得里面的內容的方式:
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里面的標簽名
兩個重要的屬性,是 name 和 attrs:
print soup.name print soup.head.name #[document] #head- 1
- 2
- 3
- 4
整個tag是一個document類型,?
其中標簽名可以通過這樣的方式獲得(再如:soup.a.name)
- 1
- 2
p 標簽的所有屬性打印輸出了出來,得到的類型是一個字典。?
.
2、基本構成——NavigableString
標簽內的文字,就是<title>The Dormouse's story</title>中的The Dormouse’s story
print soup.p.string #The Dormouse's story- 1
- 2
其中的文字相對來說就是標簽的注釋,利用 .string 來輸出它的內容。其格式為:Comment 類型
if type(soup.a.string)==bs4.element.Comment:print soup.a.string- 1
- 2
延伸:strings 實踐
一個tag僅有一個子節點,那么這個tag也可以使用 .string 方法?
如果tag中包含多個字符串 ,可以使用 .strings 來循環獲取
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
輸出結果
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、子節點——.contents .children
.contents,將tag的子節點以list列表的方式輸出。?
.children,返回的不是一個 list,是一個list生成器,
- 1
- 2
- 1
- 2
- 3
4、子孫節點——.descendants
跟.children一樣輸出的是一個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的區別,.descendants輸出的內容比較多,不僅把.children的內容輸出了 且加上了標簽內的文字:The Dormouse’s storyThe Dormouse’s story?
.
5、父節點—— .parent
通過元素的 .parents 屬性可以遞歸得到元素的所有父輩節點,例如
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、兄弟節點—— .next_sibling .previous_sibling
print soup.p.next_sibling # 實際該處為空白 print soup.p.prev_sibling #None 沒有前一個兄弟節點,返回 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> #下一個節點的下一個兄弟節點是我們可以看到的節點- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
.
7、前后節點——.next_element .previous_element
與 .next_sibling .previous_sibling 不同,它并不是針對于兄弟節點,而是在所有節點,不分層次
比如 head 節點為
<head><title>The Dormouse's story</title></head>- 1
那么它的下一個節點便是 title,它是不分層次關系的
print soup.head.next_element #<title>The Dormouse's story</title>- 1
- 2
.
三、搜索文檔樹
主要參考:Python爬蟲利器二之Beautiful Soup的用法
1、find_all( name , attrs , recursive , text , **kwargs )
搜索當前tag的所有tag子節點,并判斷是否符合過濾器的條件
(1)搜索節點
soup.find_all('b') # [<b>The Dormouse's story</b>]- 1
- 2
(2)正則表達——針對節點
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
相當于遍歷節點有啥。
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)搜索文檔中的字符串內容
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 參數——針對標簽注釋
傳入 href 參數,Beautiful Soup會搜索每個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 參數
檢索當前tag的所有子孫節點,如果只想搜索tag的直接子節點
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 參數
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實踐
有這么一段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
結果輸出:
# 第一種輸出 <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() 只搜索當前節點的所有子節點,孫子節點等. find_parents() 和 find_parent() 用來搜索當前節點的父輩節點,搜索方法與普通tag的搜索方法相同,搜索文檔搜索文檔包含的內容
find_next_siblings() find_next_sibling()- 1
這2個方法通過 .next_siblings 屬性對當 tag 的所有后面解析的兄弟 tag 節點進行迭代, find_next_siblings() 方法返回所有符合條件的后面的兄弟節點,find_next_sibling() 只返回符合條件的后面的第一個tag節點
find_previous_siblings() find_previous_sibling()- 1
這2個方法通過 .previous_siblings 屬性對當前 tag 的前面解析的兄弟 tag 節點進行迭代, find_previous_siblings() 方法返回所有符合條件的前面的兄弟節點, find_previous_sibling() 方法返回第一個符合條件的前面的兄弟節點?
.
3、select——CSS選擇器
(1)通過標簽名查找
案例一 print soup.select('title') #[<title>The Dormouse's story</title>]- 1
- 2
- 3
- 1
- 2
- 3
- 1
- 2
- 3
(2)通過類名查找
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)屬性查找
查找時還可以加入屬性元素,屬性需要用中括號括起來,注意屬性和標簽屬于同一節點,所以中間不能加空格,否則會無法匹配到。
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的用法
延伸一:實踐
# 讀入內容 contents = BeautifulSoup(open(url,'r',encoding = 'utf-8')).find_all("div",class_="caption col-md-12") #1.re庫用正則,提取標簽中的html 內容:<a target="001" class="002" href="../..//003.html">re.findall(r'\"(.*html)\"',str( content )) #2.re庫正則,在.find_all中使用 內容:<a target="001" class="002" href="../..//003.html"> re.findall(r'\"(.*html)\"',str(content.find_all("a",class_="002")[0])) #3.提取標簽下的文本內容 內容:content = <h4><a href="../../../img/56b311675fe3329a703cf9de.html">獨釣圖 可以看到該內容前面有兩個<>標簽,可以直接: content.find_all('a').strings[0]#4.相同標簽,有類別屬性 內容: <span class="a">text1<span class="b">text2 以上有兩個span相同的標簽,可以通過class來輔助定位、查找: content.find_all('span',class_='pull-right').strings # 即為文本內容#5.相同標簽,無類別屬性 內容: <span >text1<span >text2content.find_all('span').contents[0].strings 先生成一個列表,然后選中,再得到下面的文本材料# 6.奇怪的副標題 內容: <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總結
以上是生活随笔為你收集整理的python︱HTML网页解析BeautifulSoup学习笔记的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 根据”so劫持”过360加固详细分析
- 下一篇: websocket python爬虫_p