date: 2016-10-10 08:49:53
BeautifulSoup,網頁解析器,DOM樹,結構化解析。
1 安裝
BeautifulSoup4.x 兼容性不好,選用BeautifulSoup3.x + Python 2.x.
下載安裝包放在/lib文件下,DOS下輸入:
1 python setup.py build
2 python setup.py install
2 測試
IDLE里輸入:
import BeautifulSoup
print BeautifulSoup
運行顯示:
<module 'BeautifulSoup' from 'C:\Python27\lib\site-packages\BeautifulSoup.pyc'>
3 網頁解析器-BeautifulSoup-語法
由HTLM網頁可進行以下活動:
- 創建BeautifulSoup對象
- 搜索節點find_all/find
- 訪問節點名稱、屬性、文字
例如:
<a herf='123.html' class='article_link'> Python</a>
節點名稱:a
節點屬性:herf='123.html'
節點屬性:class='article_link'
節點內容:Python
4 創建BeautifulSoup對象
<pre>
import BeautifulSoup
根據HTML網頁字符串創建BeautifulSoup對象
soup = BeautifulSoup(
html_doc, #HTLM文檔字符串
'htlm.parser' #HTLM解析器
from_encoding='utf8' #HTLM文檔的編碼
)
</pre>
5 搜索節點(find_all,find)
<pre>
方法:find_all(name,attrs,string)
查找所有標簽為a的節點
soup.find_all('a')
查找所有標簽為a,鏈接符合/view/123.htlm形式的節點
soup.find_all('a',href='/view/123.htlm')
soup.find_all('a',href=re.compile(r'/view/d+.htm'))
查找所有標簽為div,class為abc,文字為Python的節點
soup.find_all('div',class_='abc',sting='Python')
</pre>
6 訪問節點信息
<pre>
得到節點:<a href='1.html'>Python</a>
獲得查找到的節點的標簽名稱
node.name
獲得查找到的a節點的href屬性
node['herf']
獲取查找到的a節點的鏈接文字
node.get_text()
</pre>
7 實例測試
#coding:utf-8
from bs4 import BeautifulSoup
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 class="sister" id="link1">Elsie</a>,
<a class="sister" id="link2">Lacie</a> and
<a class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
"""
#創建對象
soup = BeautifulSoup(html_doc, 'htlm.parser', from_encoding='utf-8') #參數:文檔字符串,解析器,指定編碼
print '獲取所有的鏈接'
links = soup.find_all('a') #獲取所有的鏈接
for link in links:
print link.name, link['href'],link.get_text() #名稱,屬性,文字