上一節咱們介紹了正則表達式,它的內容其實仍是蠻多的,若是一個正則匹配稍有差池,那可能程序就處在永久的循環之中,並且有的小夥伴們也對寫正則表達式的寫法用得不熟練,不要緊,咱們還有一個更強大的工具,叫Beautiful Soup,有了它咱們能夠很方便地提取出HTML或XML標籤中的內容,實在是方便,這一節就讓咱們一塊兒來感覺一下Beautiful Soup的強大吧。html
簡單來講,Beautiful Soup是python的一個庫,最主要的功能是從網頁抓取數據。官方解釋以下:html5
Beautiful Soup提供一些簡單的、python式的函數用來處理導航、搜索、修改分析樹等功能。它是一個工具箱,經過解析文檔爲用戶提供須要抓取的數據,由於簡單,因此不須要多少代碼就能夠寫出一個完整的應用程序。
Beautiful Soup自動將輸入文檔轉換爲Unicode編碼,輸出文檔轉換爲utf-8編碼。你不須要考慮編碼方式,除非文檔沒有指定一個編碼方式,這時,Beautiful Soup就不能自動識別編碼方式了。而後,你僅僅須要說明一下原始編碼方式就能夠了。
Beautiful Soup已成爲和lxml、html6lib同樣出色的python解釋器,爲用戶靈活地提供不一樣的解析策略或強勁的速度。
廢話很少說,咱們來試一下吧~python
Beautiful Soup 3 目前已經中止開發,推薦在如今的項目中使用Beautiful Soup 4,不過它已經被移植到BS4了,也就是說導入時咱們須要 import bs4 。因此這裏咱們用的版本是 Beautiful Soup 4.3.2 (簡稱BS4),另外聽說 BS4 對 Python3 的支持不夠好,不過我用的是 Python2.7.7,若是有小夥伴用的是 Python3 版本,能夠考慮下載 BS3 版本。正則表達式
能夠利用 pip 或者 easy_install 來安裝,如下兩種方法都可segmentfault
easy_install beautifulsoup4
pip install beautifulsoup4
若是想安裝最新的版本,請直接下載安裝包來手動安裝,也是十分方便的方法。在這裏我安裝的是 Beautiful Soup 4.3.2瀏覽器
下載完成以後解壓app
運行下面的命令便可完成安裝函數
sudo python setup.py install
而後須要安裝 lxml工具
easy_install lxml
pip install lxml
另外一個可供選擇的解析器是純Python實現的 html5lib , html5lib的解析方式與瀏覽器相同,能夠選擇下列方法來安裝html5lib:post
easy_install html5lib
pip install html5lib
Beautiful Soup支持Python標準庫中的HTML解析器,還支持一些第三方的解析器,若是咱們不安裝它,則 Python 會使用 Python默認的解析器,lxml 解析器更增強大,速度更快,推薦安裝。
在這裏先分享官方文檔連接,不過內容是有些多,也不夠條理,在此本文章作一下整理方便你們參考。
首先必需要導入 bs4 庫
from bs4 import BeautifulSoup
咱們建立一個字符串,後面的例子咱們便會用它來演示
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> """
在使用該腳本時,須要安裝下面用到的庫先,如這樣:
easy_install requests easy_install codecs easy_install bs4 easy_install openpyxl
腳本文件
#!/usr/bin/env python # encoding=utf-8 import requests,re import codecs from bs4 import BeautifulSoup from openpyxl import Workbook wb = Workbook() dest_filename = '電影.xlsx' ws1 = wb.active ws1.title = "電影top250" DOWNLOAD_URL = 'http://movie.douban.com/top250/' def download_page(url): """獲取url地址頁面內容""" headers = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 Safari/537.36' } data = requests.get(url, headers=headers).content return data def get_li(doc): soup = BeautifulSoup(doc, 'html.parser') ol = soup.find('ol', class_='grid_view') name = [] #名字 star_con = [] #評價人數 score = [] #評分 info_list = [] #短評 for i in ol.find_all('li'): detail = i.find('div', attrs={'class': 'hd'}) movie_name = detail.find('span', attrs={'class': 'title'}).get_text() #電影名字 level_star = i.find('span',attrs={'class':'rating_num'}).get_text() #評分 star = i.find('div',attrs={'class':'star'}) star_num = star.find(text=re.compile('評價')) #評價 info = i.find('span',attrs={'class':'inq'}) #短評 if info: #判斷是否有短評 info_list.append(info.get_text()) else: info_list.append('無') score.append(level_star) name.append(movie_name) star_con.append(star_num) page = soup.find('span', attrs={'class': 'next'}).find('a') #獲取下一頁 if page: return name,star_con,score,info_list,DOWNLOAD_URL + page['href'] return name,star_con,score,info_list,None def main(): url = DOWNLOAD_URL name = [] star_con=[] score = [] info = [] while url: doc = download_page(url) movie,star,level_num,info_list,url = get_li(doc) name = name + movie star_con = star_con + star score = score+level_num info = info+ info_list for (i,m,o,p) in zip(name,star_con,score,info): col_A = 'A%s'%(name.index(i)+1) col_B = 'B%s'%(name.index(i)+1) col_C = 'C%s'%(name.index(i)+1) col_D = 'D%s'%(name.index(i)+1) ws1[col_A]=i ws1[col_B] = m ws1[col_C] = o ws1[col_D] = p wb.save(filename=dest_filename) if __name__ == '__main__': main()
pip和easy_install安裝命令有什麼區別?
請看該博文:Python 包管理工具解惑
參考博文:
Beautiful Soup用法
Python 爬蟲-模擬登陸知乎-爬取拉勾網職位信息
Python 包管理工具解惑