課堂筆記-爬蟲beautifulsoup模塊

課堂筆記

1. bs4簡介

1.1 基本概念
Beautiful Soup 是一個可以從HTML或XML文件中提取數據的網頁信息提取庫
1.2 源碼分析
• github下載源碼
• 安裝
• pip install lxml
• pip install bs4

2. bs4的使用

2.1 快速開始

html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><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>
"""


# 獲取bs對象
bs = BeautifulSoup(html_doc,'lxml')
# 打印文檔內容(把我們的標籤更加規範的打印)

print(bs.prettify())
print(bs.title) # 獲取title標籤內容 <title>The Dormouse's story</title>
print(bs.title.name) # 獲取title標籤名稱 title
print(bs.title.string) # title標籤裏面的文本內容 The Dormouse's story
print(bs.p) # 獲取p段落

2.2 bs4的對象種類

• tag : 標籤
• NavigableString : 可導航的字符串
• BeautifulSoup : bs對象
• Comment : 註釋

3. 遍歷樹 遍歷子節點

bs裏面有三種情況,第一個是遍歷,第二個是查找,第三個是修改

3.1 contents children descendants

• contents 返回的是一個列表
• children 返回的是一個迭代器通過這個迭代器可以進行迭代
• descendants 返回的是一個生成器遍歷子子孫孫

3.2 .string .strings .stripped strings

• string獲取標籤裏面的內容
• strings 返回是一個生成器對象用過來獲取多個標籤內容
• stripped strings 和strings基本一致 但是它可以把多餘的空格去掉

4. 遍歷樹 遍歷父節點

parent 和 parents
• parent直接獲得父節點
• parents獲取所有的父節點

5. 遍歷樹 遍歷兄弟結點

• next_sibling 下一個兄弟結點
• previous_sibling 上一個兄弟結點
• next_siblings 下一個所有兄弟結點
• previous_siblings上一個所有兄弟結點

6. 搜索樹

• 字符串過濾器
• 正則表達式過濾器
我們用正則表達式裏面compile方法編譯一個正則表達式傳給 find 或者 findall這個方法可以實現一個正則表達式的一個過濾器的搜索
• 列表過濾器
• True過濾器
• 方法過濾器

7. find_all() 和 find()

7.1 find_all()

• find_all()方法以列表形式返回所有的搜索到的標籤數據
• find()方法返回搜索到的第一條數據
• find_all()方法參數
def find_all(self, name=None, attrs={}, recursive=True, text=None,
limit=None, **kwargs):
• name : tag名稱
• attr : 標籤的屬性
• recursive : 是否遞歸搜索
• text : 文本內容
• limli : 限制返回條數
• kwargs : 關鍵字參數

7.2 find_parents() find_parent() find_next_siblings() find_next_sibling()

• find_parents() 搜索所有父親
• find_parrent() 搜索單個父親
• find_next_siblings()搜索所有兄弟
• find_next_sibling()搜索單個兄弟

7.3 find_previous_siblings() find_previous_sibling find_all_next() find_next()

• find_previous_siblings() 往上搜索所有兄弟
• find_previous_sibling() 往上搜索單個兄弟
• find_all_next() 往下搜索所有元素
• find_next()往下查找單個元素

8. 修改文檔樹

• 修改tag的名稱和屬性
• 修改string 屬性賦值,就相當於用當前的內容替代了原來的內容
• append() 像tag中添加內容,就好像Python的列表的 .append() 方法
• decompose() 修改刪除段落,對於一些沒有必要的文章段落我們可以給他刪除掉

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章