Python 下的BeautifulSoup 库

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 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)
print(soup.prettify())
print(soup.head)
print(soup.body)





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值