爬蟲學習——網頁解析器Beautiful Soup

來源:互聯網
上載者:User

標籤:匹配   輸入   名稱   ext   htm   官方   rom   情況   模組   

一.Beautiful Soup的安裝與測試

官方網站:https://www.crummy.com/software/BeautifulSoup/

  Beautiful Soup安裝與使用文檔:  https://www.crummy.com/software/BeautifulSoup/bs4/doc/

1.首先測試一下bs4模組是否已經存在,若不存在再安裝即可,我用的是kali測試發現bs4模組已經存在,下面介紹如何測試與安裝

建立python文檔輸入以下代碼

1 import bs42 print bs4

顯示一下結果即說明bs4模組已經存在,其他情況則需要安裝

安裝代碼如下

1 sudo apt-get  install python-pip2 3 sudo pip install beautifulsoup4 

之後再進行測試即可

就會顯示出來這時就說明 Beautiful Soup

 

 安裝已經完成

二、Beautiful Soup的文法

find_all:搜尋出滿足要求的所有節點

find:搜尋出滿足要求的第一個節點

二者的參數是一樣的

2.按照節點名稱、屬性值、文字進行的搜尋

 

3.建立Beautiful Soup對象相應的代碼

 1 from bs4 import BeautifulSoup 2  3 #根據HTML網頁字串建立BreautifulSoup對象 4 soup = BeautifulSoup( 5         html_doc,                          #HTML文檔字串    6         ‘html.parser‘                      #HTML解析器 7         from_encoding=‘utf-8‘         #HTML文檔的編碼 8         )

4.搜尋節點(find_all,find)

find_all(name節點名稱,attrs節點屬性,string節點文字)

 

 1 # 方法:find_all(name,attrs,string) 2  3 #尋找所有標籤為a的節點 4 soup.find_all(‘a‘) 5  6 #尋找所有標籤為a,連結符合/view/123.html形式的節點 7 soup.find_all(‘a‘,href=‘/view/123.html‘) 8 soup.find_all(‘a‘,href=re.compile(r‘/view/\d+\.htm‘))    #bs中可以在find方法中的名稱和屬性上使用Regex來匹配對應的內容 9 10 #尋找所有標籤為div,class為abc,文字為python的節點11 soup.find_all(‘div‘,class_=‘abc‘,string=‘python‘)

 

5.得到節點後訪問節點資訊


 1 #假如得到節點:<a href=‘1.html‘>python</a> 2 3 #擷取尋找到的a節點的href屬性 4 node.name 5  6 #擷取尋找到的a節點的href屬性,以字典的形式訪問到a節點所有的屬性   7  node[‘href‘] 8 9 #擷取尋找到的a節點的連結文字
10 node.get_text()

通過以上建立bs4對象,搜尋DOM樹,訪問節點的內容,就可以實現對整個下載好的網頁

所有節點的解析和訪問。下一篇博文將給一個完整的範例程式碼

 

爬蟲學習——網頁解析器Beautiful Soup

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.