除了之前讲的Urllib、Requests之外,python中获取数据的还有Beautiful Soup库。跟前两个库的作用差不多,对于网页的提取都有很好地效果。在使用上,小编只能说,一千个人心中有一千个哈姆雷特,大家可以根据自己的学习情况和喜好,自由的选择。毕竟适合自己的才是最好的。接下来我们就开始今天的学习吧~
首先必须要导入 bs4 库
from bs4 import BeautifulSoup
我们创建一个字符串,后面的例子我们便会用它来演示
html = """ <html><head><title>The Dormouse's story</title></head> <body> <p name="dromouse"><b>The Dormouse's story</b></p> <p>Once upon a time there were three little sisters; and their names were <a href="http://example.com/elsie" id="link1"><!-- Elsie --></a>, <a href="http://example.com/lacie" id="link2">Lacie</a> and <a href="http://example.com/tillie" id="link3">Tillie</a>; and they lived at the bottom of a well.</p> <p>...</p> """
创建 beautifulsoup 对象
soup = BeautifulSoup(html)
另外,我们还可以用本地 HTML 文件来创建对象,例如
soup = BeautifulSoup(open('index.html'))
上面这句代码便是将本地 index.html 文件打开,用它来创建 soup 对象 下面我们来打印一下 soup 对象的内容,格式化输出
print soup.prettify()
输出结果:
<html> <head> <title> The Dormouse's story </title> </head> <body> <p name="dromouse"> <b> The Dormouse's story </b> </p> <p> Once upon a time there were three little sisters; and their names were <a href="http://example.com/elsie" id="link1"> <!-- Elsie --> </a> , <a href="http://example.com/lacie" id="link2"> Lacie </a> and <a href="http://example.com/tillie" id="link3"> Tillie </a> ; and they lived at the bottom of a well. </p> <p> ... </p> </body> </html>
以上就是Python爬虫中Beautiful Soup对象创建的方法。知道小伙伴们喜欢混迹于不同的网页,小编找寻资料的速度也在不在加快,只为能给大家带来最优的方法,让大家用的方便和省事~
常见问题FAQ
- 免费下载或者VIP会员专享资源能否直接商用?
- 本站所有资源版权均属于原作者所有,这里所提供资源均只能用于参考学习用,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用者承担。更多说明请参考 VIP介绍。
- 提示下载完但解压或打开不了?
- 找不到素材资源介绍文章里的示例图片?
- 模板不会安装或需要功能定制以及二次开发?
发表评论
还没有评论,快来抢沙发吧!