Beautiful Soup4库文档学习

发布时间:2020-07-11 11:55:52 作者:Eugenebo
来源:网络 阅读:543

https://www.crummy.com/software/BeautifulSoup/bs4/doc.zh/#id4

中文版BeautifulSoup库

 

作用

  1. 提取HTML和XML文档中的数据

  2. 修改、导航、查找文档

 

创建html_doc

>>> 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> 
... """

 

#使用bs4库
>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup(html_doc)
>>> print soup.prettify()
<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 class="sister" href="http://example.com/elsie" id="link1">
    Elsie
   </a>
   ,
   <a class="sister" href="http://example.com/lacie" id="link2">
    Lacie
   </a>
   and
   <a class="sister" href="http://example.com/tillie" id="link3">
    Tillie
   </a>
   ; 
and they lived at the bottom of a well.
  </p>
  <p class="story">
   ...
  </p>
 </body>
</html>

 

提取所需的字段
>>> soup.title                                                    #提取标题
<title>The Dormouse's story</title>
>>> soup.title.name
'title'


>>> soup.title.string                                            #提取标题的内容
u"The Dormouse's story"


>>> soup.a                                                        #提取<a>字段信息(第一个<a>)
<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>

>>> soup.p
<p class="title"><b>The Dormouse's story</b></p>
>>> soup.p['class']
['title']

 

查找<a>
>>> soup.find_all('a')    
[<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]

>>> for link in soup.find_all('a'):
...     print link.get('href')                        #提取link, href字段
...
http://example.com/elsie
http://example.com/lacie
http://example.com/tillie

 

 

 

 

 

 

 

 

推荐阅读:
  1. 爬虫入门之Beautiful Soup
  2. python爬虫开发之Beautiful Soup模块从安装到详细使用方法与实例

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

beautiful soup bea

上一篇:MFC第三课 多字节处理

下一篇:华为——配置OSPF实现不连续区域网络通信

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》