小编给大家分享一下Python爬虫中如何创建 beautifulsoup 对象,希望大家阅读完这篇文章后大所收获,下面让我们一起去探讨吧!
首先必须要导入 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爬虫中如何创建 beautifulsoup 对象有了一定的了解,想了解更多相关知识,欢迎关注亿速云行业资讯频道,感谢各位的阅读!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。