翼度科技»论坛 编程开发 python 查看内容

Python Beautiful Soup模块使用教程详解

5

主题

5

帖子

15

积分

新手上路

Rank: 1

积分
15
一、模块简介

Beautiful Soup 是一个可以从HTML或XML文件中提取数据的Python库.它能够通过你喜欢的转换器实现惯用的文档导航,查找,修改文档的方式.Beautiful Soup会帮你节省数小时甚至数天的工作时间.

二、方法利用


1、引入模块

  1. # 引入
  2. html_doc = """
  3. <html><head><title>The Dormouse's story</title></head>
  4. <body>
  5. <p class="title"><b>The Dormouse's story</b></p>
  6. <p class="story">Once upon a time there were three little sisters; and their names were
  7. <a href="http://example.com/elsie" rel="external nofollow"  class="sister" id="link1">Elsie</a>,
  8. <a href="http://example.com/lacie" rel="external nofollow"  class="sister" id="link2">Lacie</a> and
  9. <a href="http://example.com/tillie" rel="external nofollow"  class="sister" id="link3">Tillie</a>;
  10. and they lived at the bottom of a well.</p>
  11. <p class="story">...</p>
  12. """
  13. from bs4 import BeautifulSoup
  14. soup = BeautifulSoup(html_doc, 'html.parser')
复制代码
四种解析器


2、几个简单的浏览结构化数据的方法

#获取Tag,通俗点就是HTML中的一个个标签
  1. #获取Tag,通俗点就是HTML中的一个个标签
  2. soup.title                    # 获取整个title标签字段:<title>The Dormouse's story</title>
  3. soup.title.name               # 获取title标签名称  :title
  4. soup.title.parent.name        # 获取 title 的父级标签名称:head
  5. soup.p                        # 获取第一个p标签字段:<p class="title"><b>The Dormouse's story</b></p>
  6. soup.p['class']               # 获取第一个p中class属性值:title
  7. soup.p.get('class')           # 等价于上面
  8. soup.a                        # 获取第一个a标签字段
  9. soup.find_all('a')            # 获取所有a标签字段
  10. soup.find(id="link3")         # 获取属性id值为link3的字段
  11. soup.a['class'] = "newClass"  # 可以对这些属性和内容等等进行修改
  12. del bs.a['class']             # 还可以对这个属性进行删除
  13. soup.find('a').get('id')      # 获取class值为story的a标签中id属性的值
  14. soup.title.string             # 获取title标签的值  :The Dormouse's story
复制代码

三、具体利用


1、获取拥有指定属性的标签

  1. 方法一:获取单个属性
  2. soup.find_all('div',id="even")            # 获取所有id=even属性的div标签
  3. soup.find_all('div',attrs={'id':"even"})    # 效果同上
  4. 方法二:
  5. soup.find_all('div',id="even",class_="square")            # 获取所有id=even并且class=square属性的div标签
  6. soup.find_all('div',attrs={"id":"even","class":"square"})    # 效果同上
复制代码

2、获取标签的属性值

  1. 方法一:通过下标方式提取
  2. for link in soup.find_all('a'):
  3.     print(link['href'])        //等同于 print(link.get('href'))
  4. 方法二:利用attrs参数提取
  5. for link in soup.find_all('a'):
  6.     print(link.attrs['href'])
复制代码

3、获取标签中的内容

  1. divs = soup.find_all('div')        # 获取所有的div标签
  2. for div in divs:                   # 循环遍历div中的每一个div
  3.     a = div.find_all('a')[0]      # 查找div标签中的第一个a标签      
  4.     print(a.string)              # 输出a标签中的内容
  5. 如果结果没有正确显示,可以转换为list列表
复制代码

4、stripped_strings

去除\n换行符等其他内容 stripped_strings
  1. divs = soup.find_all('div')
  2. for div in divs:
  3.     infos = list(div.stripped_strings)        # 去掉空格换行等
  4.     bring(infos)
复制代码

四、输出


1、格式化输出prettify()

prettify() 方法将Beautiful Soup的文档树格式化后以Unicode编码输出,每个XML/HTML标签都独占一行
  1. markup = '<a href="http://example.com/" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >I linked to <i>example.com</i></a>'
  2. soup = BeautifulSoup(markup)
  3. soup.prettify()
  4. # '<html>\n <head>\n </head>\n <body>\n  <a href="http://example.com/" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >\n...'
  5. print(soup.prettify())
  6. # <html>
  7. #  <head>
  8. #  </head>
  9. #  <body>
  10. #   <a href="http://example.com/" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >
  11. #    I linked to
  12. #    <i>
  13. #     example.com
  14. #    </i>
  15. #   </a>
  16. #  </body>
  17. # </html>
复制代码

2、get_text()

如果只想得到tag中包含的文本内容,那么可以调用 get_text() 方法,这个方法获取到tag中包含的所有文版内容包括子孙tag中的内容,并将结果作为Unicode字符串返回:
  1. markup = '<a href="http://example.com/" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >\nI linked to <i>example.com</i>\n</a>'
  2. soup = BeautifulSoup(markup)
  3. soup.get_text()
  4. u'\nI linked to example.com\n'
  5. soup.i.get_text()
  6. u'example.com'
复制代码
到此这篇关于Python Beautiful Soup模块使用教程详解的文章就介绍到这了,更多相关Python Beautiful Soup内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

来源:https://www.jb51.net/article/276323.htm
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x

举报 回复 使用道具