Python 下的BeautifulSoup 库
来源:互联网 发布:康得新 财务 股票数据 编辑:程序博客网 时间:2024/05/22 16:52
Beautiful Soup 是用 Python 写的一个 HTML/XML 的解析器,它可以很好的处理不规范标记并生成剖析树。通常用来分析爬虫抓取的web文档。对于 不规则的 Html文档,也有很多的补全功能,节省了开发者的时间和精力。Beautiful Soup 的官方文档齐全,将官方给出的例子实践一遍就能掌握。一 安装 Beautiful Soup安装 BeautifulSoup 很简单,下载 BeautifulSoup 源码。解压运行python setup.py install 即可。注意到soup相当于一个存储了html的数据结构,获取 标记对象(Tag)标记名获取法 ,直接用 soup对象加标记名,返回 tag对象.这种方式,选取唯一标签的时候比较有用。或者根据树的结构去选取,一层层的选择可以用html的标签如head,body ,title等来获取标签里面的内容,如 print(soup.html) print(soup.body) 搜索方法搜索提供了两个方法,一个是 find,一个是findAll。这里的两个方法(findAll和 find)仅对Tag对象以及,顶层剖析对象有效,但 NavigableString不可用。也可以用某个str来完成搜索任务:soup.find_all('a') soup.find(id='link3')等用find得到某个标签,但是不能直接操作标签,然后可以使用get获取标签中的信息soup = BeautifulSoup(conte)print(soup.prettify())for url in soup.find_all('img'): print(url.get('src'))开始时候得到标签 url是 <img height="260" src="http://s1.dwstatic.com/group1/M00/72/8C/6f5fcb184a590b3a996aa9ae94a8ebfd.jpg"/>使用get之后得到图片的url地址:http://s1.dwstatic.com/group1/M00/72/8C/6f5fcb184a590b3a996aa9ae94a8ebfd.jpg用 soup.get_text()可以得到html标签中的内容,如 <body> hello world</body>可以得到 hello world测试安装是否成功。键入 import BeautifulSoup 如果没有异常,即成功安装目前已经到了beautifulsoup4-4.3.1了
官方给出的例子:注意到在版本4之后,模块名称为bs4 ,import bs4
from bs4 import BeautifulSouphtml_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)print(soup.prettify())print(soup.head)print(soup.body)
- Python 下的BeautifulSoup 库
- windows8.1 下安装 python BeautifulSoup库
- Python 网页爬虫-BeautifulSoup库的学习
- Python库beautifulsoup的安装与使用
- python BeautifulSoup的安装
- python的BeautifulSoup用法
- Python的BeautifulSoup安装
- Ubuntu下python的BeautifulSoup和Mechanize安装方法
- centos下安装python的beautifulsoup、request、lxml插件
- python BeautifulSoup 库 笔记
- python BeautifulSoup 库安装
- Python BeautifulSoup库
- Python BeautifulSoup库 API
- python BeautifulSoup模块的安装
- python beautifulsoup的安装导入
- python BeautifulSoup模块的安装
- python BeautifulSoup模块的安装
- python BeautifulSoup的简单用法
- 用 PS 复制权限
- 将gvim打造成txt编辑利器
- C++函数CString::find
- 使用logmnr对其它用户的操作执行日志挖掘的四个对比实验
- codeblock 中如何改变注释颜色
- Python 下的BeautifulSoup 库
- 判断一个序列是不是另外一个序列的栈的pop序列
- 二进制转成十六进制
- 最短路径 Part I- Single source shortest path
- 读鸟哥私房菜(四)
- Git详解之一:Git起步
- NIB 和 XIB 的区别
- DCB学习之二(ETS,DCBX)
- 移动建站工具(二):分秒钟DIY一个移动网站