配置BeautifulSoup4+lxml+html5lib


 

Beautiful Soup 是一個可以從HTML或XML文件中提取數據的Python庫.它能夠通過你喜歡的轉換器實現慣用的文檔導航,查找,修改文檔的方式.Beautiful Soup會幫你節省數小時甚至數天的工作時間。
Beautiful Soup支持Python標准庫中的HTML解析器,還支持一些第三方的解析器,其中一個是 lxml 。
另一個可供選擇的解析器是純Python實現的 html5lib , html5lib的解析方式與瀏覽器相同。

Windows平台 + Python3.5

 

安裝BeautifulSoup4

方法一:打開cmd,運行pip install BeautifulSoup4
如上圖所示,由於我已經安裝過了。可以使用 --upgrade來升級為最新版本。
 
方法二:去官網 BeautifulSoup4源碼下載 -- 戳我吧!下載源碼,編譯運行。
 
至此,便安裝完畢。
驗證成功,編譯一個.py文件,輸入from bs4 import BeautifulSoup4,不會報錯即代表安裝成功。
 

安裝html5lib

第二步,我們安裝網頁文件解析器htm5lib,只需直接運行pip install html5lib即可:
 

安裝lxml

在Windows下,安裝lxml費了一點勁兒,不能直接通過命令成功安裝。我們需要去官方網站下載與平台完全一致的版本,手動安裝。
首先,查看我們的平台依賴的工具版本:
 
然后,去官網下載對應的.whl文件。 lxml 官方下載鏈接,請猛戳我~~~
Ctrl + F,輸入lxml,找到下面這段:
Lxml, a binding for the libxml2 and libxslt libraries.
lxml‑3.4.4‑cp27‑none‑win32.whl
lxml‑3.4.4‑cp27‑none‑win_amd64.whl
lxml‑3.4.4‑cp33‑none‑win32.whl
lxml‑3.4.4‑cp33‑none‑win_amd64.whl
lxml‑3.4.4‑cp34‑none‑win32.whl
lxml‑3.4.4‑cp34‑none‑win_amd64.whl
lxml‑3.4.4‑cp35‑none‑win32.whl
lxml‑3.4.4‑cp35‑none‑win_amd64.whl
cp后面是Python的版本號,27表示2.7,根據你的Python版本選擇下載。

最后進行安裝,打開cmd,先運行pip install wheel安裝wheel工具,做好准備工作。
接着運行pip install *.whl文件,我的對應版本為lxml-3.6.0-cp35-cp35m-win_amd64.whl即可成功安裝lxml解析器。
 
至此,三個工具都安裝完畢。
對於Linux平台下,安裝就很簡單了,直接利用三個命令即可完成:
  • pip install BeautifulSoup4 或 easy_install BeautifulSoup4
  • pip install html5lib
  • pip install lxml
 

使用BeautifulSoup

我們編輯一段html文檔,利用BeautifulSoup庫進行解析:
  1.  
    html = """
  2.  
    <html><head><title>The Dormouse's story</title></head>
  3.  
    <body>
  4.  
    <p class="title"><b>The Dormouse's story</b></p>
  5.  
     
  6.  
    <p class="story">Once upon a time there were three little sisters; and their names were
  7.  
    <a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
  8.  
    <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
  9.  
    <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
  10.  
    and they lived at the bottom of a well. </p>
  11.  
     
  12.  
    <p class="story">...</p>
  13.  
    """
  14.  
     
  15.  
    from bs4 import BeautifulSoup
  16.  
     
  17.  
    #添加一個解析器
  18.  
    soup = BeautifulSoup(html,'html5lib')
  19.  
    print(soup.title)
  20.  
    print(soup.title.name)
  21.  
    print(soup.title.text)
  22.  
    print(soup.body)
  23.  
     
  24.  
    #從文檔中找到所有 <a>標簽的內容
  25.  
    for link in soup.find_all('a'):
  26.  
    print(link.get('href'))
  27.  
     
  28.  
     
  29.  
    #從文檔中找到所有文字內容
  30.  
    print(soup.get_text())
注意:
在聲明BeautifulSoup對象的時候要明確解析器 soup = BeautifulSoup(html,'html5lib'),否則寫為 soup = BeautifulSoup(html) 會有警告。
 


運行上述代碼:
我們發現,BeautifulSoup可以十分方便的提取Html的結構化數據。這就為我們解析網頁文件內容,爬取目標元素提供了極大的幫助。
 
這只是一個小小的例子,BeautifulSoup庫的功能十分強大,趕緊去官方文檔學習吧~


免責聲明!

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



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