网页解析器

从网页中提取有价值数据的工具

网页解析器种类

  • 正则表达式 (模糊匹配)
  • html.parser (结构化解析)
  • BeautifulSoup第三方插件 (结构化解析,相对比较强大)
  • lxml第三方插件 (结构化解析)

【结构化解析-DOM(Document Object Model)树】

Beautiful Soup

Python第三方库,用于从HTML或XML中提取数据

语法

  1. 根据下载好的HTML网页的字符串创建BeautifulSoup对象(创建的同时就已经将整个文档整理成DOM树):
  2. 根据DOM树进行各种节点的搜索(按照节点名称,节点属性,节点文字进行搜索):两种方法
    • find_all: 搜索出所有满足要求的节点
    • find : 只搜索出第一个满足要求的节点
  3. 访问得到节点的名称,属性,文字

代码

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()

最新文章

  1. [译]Atlassian Git系列教程
  2. HBase查找一条数据的过程
  3. 动手搭个wordpress
  4. (function($, window, document) {}) jQuery 调用解决与其他javascript库冲突的写法
  5. Android中回调接口的使用
  6. VS2010远程调试
  7. QString和char字符数组之间的转换(QTextCodec.toUnicode方法,特别注意\0的问题)
  8. WebKit JavaScript Binding添加新DOM对象的三种方式
  9. mysqlbinlog查看 binlog日志报错mysqlbinlog: unknown variable &#39;default-character-set=utf8mb4&#39;
  10. require(),include(),require_once()和include_once()之间的区别
  11. arcmap从excel坐标数据生成点shp文件
  12. mysql存储过程及经常使用函数
  13. 如何在 Windows Phone 8 中获取手机的当前位置
  14. 2.Node.js access_token的获取、存储及更新
  15. json-java处理-jackson
  16. Connection reset by peer的常见原因
  17. MySQL InnoDB 备份与恢复七种方式
  18. 生命不息,折腾不止 ~ 旧PC改造之家庭影音
  19. vscode eslint配置vue遇到的问题
  20. 更改centos源为aliyun

热门文章

  1. 使用命令创建github代码仓库,push本地仓库到github远程代码仓库
  2. dotnet调用node.js写的socket服务(websocket/socket/socket.io)
  3. UVa 10041 - Vito&#39;s Family
  4. spark 中的RDD编程 -以下基于Java api
  5. Chrome 控制台 如何调试javascript
  6. HTML 样式- CSS
  7. Sublime Text3 高亮显示Jade语法 (Windows 环境)
  8. doubango(6)--Doubango协议栈中对RTP的管理
  9. 部署AlwaysOn第一步:搭建Windows服务器故障转移集群
  10. css,html性能优化