爬虫入门(三):BeautifulSoup
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 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>
"""
#创建对象
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() #名称,属性,文字