python Beautiful Soup4(一)
来源:互联网 发布:ubuntu中文输入法错误 编辑:程序博客网 时间:2024/05/22 05:22
Beautiful Soup是python的一个解析HTML或XML格式文件的包,Beautiful Soup 3已经不在开发,现在一般使用Beautiful Soup 4。学习BS4最好的方法是找一段网页例子来进行解析,我们先来写一段HTML代码。
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>父亲</title> <link rel="stylesheet" type="text/css" href="father.css"> <link rel="stylesheet" type="text/css" href="./css/bootsrap.min.css"></head><body background="./image/bg.jpg"><div id='head1'><h1>亲爱的父亲,我想对你说:</h1></div> <div> <ui> <li class="item1">感谢一路上有你!!!</li> <li class="item2">感谢一路上有你!!!</li> <li class="item3">感谢一路上有你!!!</li> <li class="item4">感谢一路上有你!!!</li> <li class="item5">感谢一路上有你!!!</li> <li class="item6">感谢一路上有你!!!</li> <li class="item7">感谢一路上有你!!!</li> <li class="item8">感谢一路上有你!!!</li> <li class="item9">感谢一路上有你!!!</li> <li class="item10">感谢一路上有你!!!</li> </ui> </div></body></html>
我们将上边的代码保存成’father.html’, 然后用BS4来解析它。
>>> from bs4 import BeautifulSoup>>> html_doc = open('father.html').read()>>> soup = BeautifulSoup(html_doc)# 直接传入文件句柄也是可以的# soup = BeautifulSoup(open('father.html')) 跟上边效果一样
现在通过BeautifulSoup的解析就可以得到一个BeautifulSoup对象,使用该对象的prettify方法,可以将代码按照标准缩进打印出来。
是不是很漂亮-_-
有了包含网页信息的BeautifulSoup对象,我们就可以愉快的解析网页了,先来几个小栗子尝尝-_-
>>> soup.title #输出文档title,含标签<title>父亲</title>>>> print soup.title.string #输出title内容父亲>>> soup.find_all('li')[<li class="item1">感谢一路上有你!!!</li>, <li class="item2">感谢一路上有你!!!</li>, <li class="item3">感谢一路上有你!!!</li>, <li class="item4">感谢一路上有你!!!</li>, <li class="item5">感谢一路上有你!!!</li>, <li class="item6">感谢一路上有你!!!</li>, <li class="item7">感谢一路上有你!!!</li>, <li class="item8">感谢一路上有你!!!</li>, <li class="item9">感谢一路上有你!!!</li>, <li class="item10">感谢一路上有你!!!</li>]
有了BS4, 就不用我们自己去编写正则表达式来解析网页了,是不是很方便呢。
0 0
- python Beautiful Soup4(一)
- Beautiful Soup4的简单使用
- python3 windows 10 Beautiful Soup4 安装指南
- Beautiful Soup4 之table数据提取
- Ubuntu系统下安装beautiful Soup4
- 一、Python's "Beautiful Heart"
- beautiful python
- Beautiful Soup(一)--基础入门
- Beautiful Soup -- 文档笔记(一)
- python Beautiful Soup文档
- Python Beautiful Soup简介
- Python Beautiful Soup Example
- [Python]安装Beautiful Soup
- python 安装 Beautiful Soup
- Python模块Beautiful Soup
- Python爬虫入门(8):Beautiful Soup的用法
- Python爬虫入门(8):Beautiful Soup的用法
- Beautiful Soup 示例解析html文件(python)
- Hadoop 1.x启动服务的顺序学习
- 基于ThinkPHP3.2的邮箱激活
- 2016年1月14日实习日志
- QT子窗体占用系统资源的释放问题 .
- Python处理excel表格
- python Beautiful Soup4(一)
- vc++ 读取指定文件夹下所有文件名
- 在scroll下面固定Button的方法
- Linux下媒体文件播放问题
- php 数组操作
- 安卓中根据图片文件名获取图片资源ID
- Cookie/Session机制详解
- android初接触之activity2
- JAVA开发中遇到的jdk配置正确但是tomcat服务器启动时一闪而过