Python之Html解析方法



一、強大的BeautifulSoupBeautifulSoup是一個可以從htmlxml文件中提取數據的Python庫。它能夠通過你喜歡的轉換器實現慣用的文檔導航、查找、修改文檔的方式。在Python開發中,主要用的是BeautifulSoup的查找提取功能,修改功能很少使用

1、安裝BeautifulSoup

pip3 install beautifulsoup4

2、安裝第三方html解析器lxml

pip3 install lxml

3、安裝純Python實現的html5lib解析器

pip3 install html5lib


二、BeautifulSoup的使用:

1、導入bs4

from bs4 import BeautifulSoup #導入bs4

2、創建包含html代碼的字符串

html_str = """

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

<body>

<p class="title"><b>The Dormouse's stopy</b></p>

<p class="story">Once upon a time there were three little sisters;and their names where

<a href="http://example.com/elsie" class="sister" id="link1"><!--Elsie--></a>

"""

3、創建BeautifulSoup對象

1)直接通過字符串方式創建

soup = BeautifulSoup(html_str,'lxml') #html.parser是解析器,也可是lxml

print(soup.prettify()) ------>輸出soup對象的內容


2)通過已有的文件來創建

soup = BeautifulSoup(open('/home/index.html'),features='html.parser')#html.parser是解析器,也可是lxml

4BeautifulSoup對象的種類:BeautifulSoup將復雜HTML文檔轉換成一個復雜的樹形結構,每個節點都是Python對象

1BeautifulSoup表示的是一個文檔的全部內容。大部分時候,可以把它當作Tag對象,是一個特殊的Tag,因為BeautifulSoup對象並不是真正的HTMLXML,所以沒有nameattribute屬性

2Tag:與XMLHTML原生文檔中的Tag相同,通俗講就是標記

如:

抽取titleprintsoup.title

抽取a printsoup.a

抽取pprintsoup.p

Tag中有兩個重要的屬性:nameattributes。每個Tag都有自己的名字,通過.name來獲取

printsoup.title.name

操作Tag屬性的方法和操作字典相同

如:<p class=’p1’>Hello World</p>

printsoup.p[‘class’]

也可以直接“點”取屬性,如 .attrs 獲取Tag中所有屬性

printsoup.p.attrs

3NavigableString:獲取標記內部的文字.string

BeautifulSoupNavigableString類來封裝Tag中的字符串,一個 NavigableString字符串與Python中的Unicode字符串相同,通過unicode()方法可以直接將 NavigableString對象轉換成Unicode字符串

如:u_string = unicode(soup.p.string)

4Comment:對於一些特殊對象,如果不清楚這個標記.string的情況下,可能造成數據提取混亂。因此在提取字符串時,可以判斷下類型:

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

print(soup.a.string)

5、遍歷文檔

1子節點:

A、對於直接子節點可以通過 .contents .children來訪問

.contents ---->Tag子節點以列表的方式輸出

printsoup.head.contents

.children ----->返回一個生成器,對Tag子節點進行循環

for child in soup.head.children:

printchild

B、獲取子節點的內容

.string ---> 如果標記里沒有標記了,則返回內容;如果標記里只有一個唯一的標記,則返回最里面的內容;如果包含多個子節點,Tag無法確定.string方法應該返回哪個時,則返回None

.strings ---->主要應用於Tag中包含多個字符串的情況,可以進行循環遍歷

for str in soup.strings:

printrepr(str)


.stripped_string ----->可以去掉字符串中包含的空格或空行

for str in soup.stripped_strings:

print(repr(str))

2父節點

A、通過.parent屬性來獲取某個元素的父節點,如:

printsoup.title.parent

B、通過.parents屬性可以遞歸得到元素的所有父輩節點

for parent in soup.a.parents:

if parent is None:

print(parent)

else:

print(parent.name)

3兄弟節點

. next_sibling ----->獲取該節點的下一個兄弟節點

. previous_sibling ----->獲取該節點的上一個兄弟節點

4前后節點

. next_elements ----->獲得該節點前面的所有節點

. previous_elements ----->獲得該節點后面的所有節點

 

6、搜索文檔樹

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

Aname參數:查找名字為name的標記

printsoup.find_all(‘‘’’b)

Btext參數:查找文檔中字符串的內容

Crecursive參數:檢索當前Tag的所有子孫節點時,若只想找直接子節點, 該參數設置為False


7CSS選擇器:使用soup.select()函數

1通過標記名查找

printsoup.select("title")

2通過Tagclass屬性值查找

printsoup.select(".sister")

3通過Tagid屬性值查找

printsoup.select("#sister")

4通過是否存在某個屬性查找

printsoup.select("a[href]")

5通過屬性值查找

printsoup.select('a[href="http://exam.com"]')

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM