Python-爬蟲-Beautifulsoup解析

簡介

Beautiful Soup 是一個能夠從HTML或XML文件中提取數據的Python庫.它可以經過你喜歡的轉換器實現慣用的文檔導航,查找,修改文檔的方式.Beautiful Soup會幫你節省數小時甚至數天的工做時間.你可能在尋找 Beautiful Soup3 的文檔,Beautiful Soup 3 目前已經中止開發,官網推薦在如今的項目中使用Beautiful Soup 4, 移植到BS4html

複製代碼
#安裝 Beautiful Soup
pip install beautifulsoup4

#安裝解析器
Beautiful Soup支持Python標準庫中的HTML解析器,還支持一些第三方的解析器,其中一個是 lxml .根據操做系統不一樣,能夠選擇下列方法來安裝lxml:

$ apt-get install Python-lxml

$ easy_install lxml

$ pip install lxml

另外一個可供選擇的解析器是純Python實現的 html5lib , html5lib的解析方式與瀏覽器相同,能夠選擇下列方法來安裝html5lib:

$ apt-get install Python-html5lib

$ easy_install html5lib

$ pip install html5lib

基本使用

複製代碼
from bs4 import BeautifulSoup
import requests,re
req_obj = requests.get('https://www.baidu.com')
soup = BeautifulSoup(req_obj.text,'lxml')

'''標籤查找'''
print(soup.title) #只是查找出第一個
print(soup.find('title')) #效果和上面同樣
print(soup.find_all('div')) #查出全部的div標籤

'''獲取標籤裏的屬性'''
tag = soup.div
print(tag['class']) #多屬性的話,會返回一個列表
print(tag['id']) #查找標籤的id屬性
print(tag.attrs) #查找標籤全部的屬性,返回一個字典(屬性名:屬性值)

'''標籤包的字符串'''
tag = soup.title
print(tag.string) #獲取標籤裏的字符串
tag.string.replace_with("哈哈") #字符串不能直接編輯,能夠替換

'''子節點的操做'''
tag = soup.head
print(tag.title) #獲取head標籤後再獲取它包含的子標籤

'''contents 和 .children'''
tag = soup.body
print(tag.contents) #將標籤的子節點以列表返回
print([child for child in tag.children]) #輸出和上面同樣


'''descendants'''
tag = soup.body
[print(child_tag) for child_tag in tag.descendants] #獲取全部子節點和子子節點

'''strings和.stripped_strings'''
tag = soup.body
[print(str) for str in tag.strings] #輸出全部全部文本內容
[print(str) for str in tag.stripped_strings] #輸出全部全部文本內容,去除空格或空行

'''.parent和.parents'''
tag = soup.title
print(tag.parent)               #輸出便籤的父標籤
[print(parent) for parent in tag.parents] #輸出全部的父標籤

'''.next_siblings 和 .previous_siblings
查出全部的兄弟節點
'''

'''.next_element 和 .previous_element
下一個兄弟節點
'''

'''find_all的keyword 參數'''
soup.find_all(id='link2') #查找全部包含 id 屬性的標籤
soup.find_all(href=re.compile("elsie")) #href 參數,Beautiful Soup會搜索每一個標籤的href屬性:
soup.find_all(id=True) #找出全部的有id屬性的標籤
soup.find_all(href=re.compile("elsie"), id='link1') #也能夠組合查找
soup.find_all(attrs={"屬性名": "屬性值"}) #也能夠經過字典的方式查找
複製代碼

 

Practice

from bs4 import BeautifulSoup as bs
import urllib.request
data=urllib.request.urlopen("http://edu.iqianyue.com/").read().decode("utf-8","ignore")
bs1=bs(data)
#格式化輸出
#print(bs1.prettify())
#獲取標籤:bs對象.標籤名
bs1.title
#獲取標籤裏面的文字:bs對象.標籤名.string
bs1.title.string
#獲取標籤名:bs對象.標籤名.name
bs1.title.name
#獲取屬性列表:bs對象.標籤名.attrs
bs1.a.attrs
#獲取某個屬性對應的值:bs對象.標籤名[屬性名] 或者 bs對象.標籤名.get(屬性名)
bs1.a["class"]
bs1.a.get("class")
#提取全部某個節點的內容:bs對象.find_all('標籤名') bs對象.find_all(['標籤名1','標籤名2,…,標籤n'])
bs1.find_all('a')
bs1.find_all(['a','ul'])
#提取全部子節點:bs對象.標籤.contents bs對象.標籤.children
k1=bs1.ul.contents
k2=bs1.ul.children
allulc=[i for i in k2]
#更多信息能夠閱讀官方文檔:http://beautifulsoup.readthedocs.io/zh_CN/latest/
相關文章
相關標籤/搜索