Beautifulsoup4庫學習(原文)
爬蟲
Beautiful Soup
一個的英文可以從HTML
或XML
文件中提取數據的Python
庫它能夠通過你喜歡的轉換器實現慣用的文檔導航,查找,修改文檔的方式。
參考:中文文檔
HTML演示代碼
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>
"""
基本用法
from bs4 import BeautifulSoup # 解析html,官方推薦寫法
soup = BeautifulSoup(html_doc, 'lxml') # 以lxml解析器解析,本地導入寫法
#soup = BeautifulSoup(open("index.html"))
soup.prettify() # 補全html代碼,容錯。
print(soup.prettify())
print(soup.p) # 第一個p標籤
print(soup.a)
print(soup.title.string) #標題內容
print(soup.title.name) # 標題的名稱
print(soup.head)
print(soup.p['class']) # p標籤下class屬性的值
soup.find_all('a') # 找到所有a標籤
soup.find(id="link3") # 找到id值是link3的標籤
for link in soup.find_all('a'):
print(link.get('href'))
print(soup.get_text()) # 從soup中獲取文字
遍歷文檔樹
1、tag的content屬性可以將tag的子節點和子孫節點以**列表**的方式輸出
print(soup.p.contents)
print(soup.p.contents[1])
2、children返回的不是一個 list,不過我們可以通過遍歷獲取所有子節點,它是一個 list 生成器對象,i是索引,child是內容。
for i,child in enumenerate(soup.p.children):
print(i,child)
3、通過子節點可獲得其父節點,祖先節點,以及上下兄弟節點
soup.a.parent
soup.a.parents
soup.a.next_sliblings (下一個)
soup.a.previous_sliblings (上一個)
4,尋找節點,以下幾種傳遞方式
soup.find_all('a') # 找到所有a標籤
print(soup.find_all("a", limit=2)) #限制搜索結果數
for link in soup.find_all('a'):
print(link.get('href'))
soup.find_all(id='1')
soup.find_all(class_='name')#關鍵字 class 在Python中是保留字,使用 class 做參數會導致語法錯誤,可用class_
soup.find_all(text='文本')
print(soup.find_all(['title','b'])) # 傳遞列表進去,匹配到同時又兩個標籤相同的標籤
import re
'''傳遞正則表達式'''
for tag in soup.find_all(re.compile("^b")):
print(tag.name)
print(soup.find_all(attrs={"class":"title"}))#attrs參數,定義一個字典參數來搜索包含特殊屬性的tag
5,css選擇器
soup.select("title")
soup.select("p:nth-of-type(3)")