1. 程式人生 > >python︱HTML網頁解析BeautifulSoup學習筆記

python︱HTML網頁解析BeautifulSoup學習筆記

一、載入html頁面資訊

一種是網站線上的網頁、一種是下載下來的靜態網頁。

1、線上網頁

import requests
from bs4 import BeautifulSoup

headers={'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:頁面的內容

2、本地的靜態頁面

url = ...\...\...
soup = BeautifulSoup(open(url,'r',encoding = 'utf-8'))

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、基本構成——Tag

就是 HTML 中的一個個標籤

<title>The Dormouse's story</title>

以上整個叫做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>

其中title,head,p,a都是tag裡面的標籤名

兩個重要的屬性,是 name 和 attrs:

print soup.name
print soup.head.name
#[document]
#head

整個tag是一個document型別,
其中標籤名可以通過這樣的方式獲得(再如:soup.a.name)

print soup.p.attrs
#{'class': ['title'], 'name': 'dromouse'}

p 標籤的所有屬性列印輸出了出來,得到的型別是一個字典。
.

2、基本構成——NavigableString

標籤內的文字,就是<title>The Dormouse's story</title>中的The Dormouse’s story

print soup.p.string
#The Dormouse's story

其中的文字相對來說就是標籤的註釋,利用 .string 來輸出它的內容。其格式為:Comment 型別

if type(soup.a.string)==bs4.element.Comment:
    print soup.a.string

延伸:strings 實踐

一個tag僅有一個子節點,那麼這個tag也可以使用 .string 方法
如果tag中包含多個字串 ,可以使用 .strings 來迴圈獲取


combine_html = """
 <p class="identical">
  Example of p tag with class identical
 </p>
 <div class="identical">
  Example of div tag with class identical
 <div>
 """

輸出結果

list(combine_soup.strings)

['\n  Example of p tag with class identical\n ',
 '\n',
 '\n  Example of div tag with class identical\n ',
 '\n']

.

3、子節點——.contents .children

.contents,將tag的子節點以list列表的方式輸出。
.children,返回的不是一個 list,是一個list生成器,

print soup.head.contents 
#[<title>The Dormouse's story</title>]
for child in  soup.body.children:
    print child
#<p class="title" name="dromouse"><b>The Dormouse's story</b></p>

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>

可以看到與.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]

.

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>
#下一個節點的下一個兄弟節點是我們可以看到的節點

.

7、前後節點——.next_element .previous_element

與 .next_sibling .previous_sibling 不同,它並不是針對於兄弟節點,而是在所有節點,不分層次

比如 head 節點為

<head><title>The Dormouse's story</title></head>

那麼它的下一個節點便是 title,它是不分層次關係的

print soup.head.next_element
#<title>The Dormouse's story</title>

.

三、搜尋文件樹

1、find_all( name , attrs , recursive , text , **kwargs )

搜尋當前tag的所有tag子節點,並判斷是否符合過濾器的條件

(1)搜尋節點

soup.find_all('b')
# [<b>The Dormouse's story</b>]

(2)正則表達——針對節點

import re
for tag in soup.find_all(re.compile("^b")):
    print(tag.name)
# body
# b

(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>]

(4)傳 True

相當於遍歷節點有啥。

for tag in soup.find_all(True):
    print(tag.name)
# html
# head
# title
# body
# p
# b
# p
# a
# a

(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"]

(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>]

(7)recursive 引數

檢索當前tag的所有子孫節點,如果只想搜尋tag的直接子節點

soup.html.find_all("title")
# [<title>The Dormouse's story</title>]

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

(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>]

延伸一: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")   

結果輸出:

# 第一種輸出
<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>]

.

2、其他 find

find_parents()  find_parent()

find_all() 和 find() 只搜尋當前節點的所有子節點,孫子節點等. find_parents() 和 find_parent() 用來搜尋當前節點的父輩節點,搜尋方法與普通tag的搜尋方法相同,搜尋文件搜尋文件包含的內容

find_next_siblings()  find_next_sibling()

這2個方法通過 .next_siblings 屬性對當 tag 的所有後面解析的兄弟 tag 節點進行迭代, find_next_siblings() 方法返回所有符合條件的後面的兄弟節點,find_next_sibling() 只返回符合條件的後面的第一個tag節點

find_previous_siblings()  find_previous_sibling()

這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>]
# 案例二
print soup.select('a')
#[<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>]
# 案例三
print soup.select('b')
#[<b>The Dormouse's story</b>]

(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>]

(3)id查詢

print soup.select('#link1')
#[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>]

(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>]

print soup.select('p a[href="http://example.com/elsie"]')
#[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>]

.

主要參考:

延伸一:實踐

#  讀入內容
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]
#另一種:
'[<a href="#1">簡介</a>]'.get_text()
>>> 簡介


#4.相同標籤,有類別屬性
內容: <span class="a">text1
        <span class="b">text2
以上有兩個span相同的標籤,可以通過class來輔助定位、查詢:
content.find_all('span',class_='pull-right').strings  # 即為文字內容

#5.相同標籤,無類別屬性
內容: <span >text1
        <span >text2

content.find_all('span').contents[0].strings
先生成一個列表,然後選中,再得到下面的文字材料

# 6.奇怪的副標題
內容: <td width="285" valign="top">17641815</td>
content.find_all('td',width="285", valign="top")