Python爬虫中如何创建beautifulsoup对象-创新互联

小编给大家分享一下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 对象有了一定的了解,想了解更多相关知识,欢迎关注创新互联行业资讯频道,感谢各位的阅读!

新闻标题:Python爬虫中如何创建beautifulsoup对象-创新互联
路径分享:https://www.cdcxhl.com/article44/dpgihe.html

成都网站建设公司_创新互联,为您提供微信小程序标签优化网站收录App开发服务器托管面包屑导航

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联

网站优化排名