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)
	
				
		
原创粉丝点击