网页解析器
从网页中提取有价值数据的工具
网页解析器种类
- 正则表达式 (模糊匹配)
- html.parser (结构化解析)
- BeautifulSoup第三方插件 (结构化解析,相对比较强大)
- lxml第三方插件 (结构化解析)
【结构化解析-DOM(Document Object Model)树】
Beautiful Soup
Python第三方库,用于从HTML或XML中提取数据
语法
- 根据下载好的HTML网页的字符串创建BeautifulSoup对象(创建的同时就已经将整个文档整理成DOM树):
- 根据DOM树进行各种节点的搜索(按照节点名称,节点属性,节点文字进行搜索):两种方法
- find_all: 搜索出所有满足要求的节点
- find : 只搜索出第一个满足要求的节点
- 访问得到节点的名称,属性,文字
代码
import urllib2
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,# HTML文档字符串
'html.parser', # HTML解析器
from_encoding = 'utf-8' # HTML文档的编码
)
print '获取所有的链接'
links = soup.find_all('a')
for link in links:
print link.name,link['href'],link.get_text()
print '获取Lacie的链接'
link_node = soup.find('a',href = 'http://example.com/lacie')
print link_node.name,link_node['href'],link_node.get_text()
print '正则匹配'
print '获取p段落文字'
p_node = soup.find('p',class_='story')
print p_node.name,p_node.get_text()