BeautifulSoup库入门

一.准备

首先得安装好bs4库,然后引入BeautifulSoup。

from bs4 import BeautifulSoup

二.使用

BeautifulSoup库是解析、遍历、维护“标签树”的功能库。

“标签树”就是HTML代码,因为它带有标签而且层次分明,所以形象的把它叫做“标签树”。

在这里插入图片描述


(1)获取HTML文本

使用前我们要先得到HTML代码,操作如下(以baidu.com为例):

import requests
from bs4 import BeautifulSoup

url = "https://baidu.com" #网址
r = requests.get(url)
r.encoding = r.apparent_encoding #使其正常显示,不会出现乱码
html = r.text
print(html)

得到HTML代码如下:

'<!DOCTYPE html>\r\n<!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta content=always name=referrer><link rel=stylesheet type=text/css href=http://s1.bdstatic.com/r/www/cache/bdorz/baidu.min.css><title>百度一下,你就知道</title></head> <body link=#0000cc> <div id=wrapper> <div id=head> <div class=head_wrapper> <div class=s_form> <div class=s_form_wrapper> <div id=lg> <img hidefocus=true src=//www.baidu.com/img/bd_logo1.png width=270 height=129> </div> <form id=form name=f action=//www.baidu.com/s class=fm> <input type=hidden name=bdorz_come value=1> <input type=hidden name=ie value=utf-8> <input type=hidden name=f value=8> <input type=hidden name=rsv_bp value=1> <input type=hidden name=rsv_idx value=1> <input type=hidden name=tn value=baidu><span class="bg s_ipt_wr"><input id=kw name=wd class=s_ipt value maxlength=255 autocomplete=off autofocus></span><span class="bg s_btn_wr"><input type=submit id=su value=百度一下 class="bg s_btn"></span> </form> </div> </div> <div id=u1> <a href=http://news.baidu.com name=tj_trnews class=mnav>新闻</a> <a href=http://www.hao123.com name=tj_trhao123 class=mnav>hao123</a> <a href=http://map.baidu.com name=tj_trmap class=mnav>地图</a> <a href=http://v.baidu.com name=tj_trvideo class=mnav>视频</a> <a href=http://tieba.baidu.com name=tj_trtieba class=mnav>贴吧</a> <noscript> <a href=http://www.baidu.com/bdorz/login.gif?login&amp;tpl=mn&amp;u=http%3A%2F%2Fwww.baidu.com%2f%3fbdorz_come%3d1 name=tj_login class=lb>登录</a> </noscript> <script>document.write(\'<a href="http://www.baidu.com/bdorz/login.gif?login&tpl=mn&u=\'+ encodeURIComponent(window.location.href+ (window.location.search === "" ? "?" : "&")+ "bdorz_come=1")+ \'" name="tj_login" class="lb">登录</a>\');</script> <a href=//www.baidu.com/more/ name=tj_briicon class=bri style="display: block;">更多产品</a> </div> </div> </div> <div id=ftCon> <div id=ftConw> <p id=lh> <a href=http://home.baidu.com>关于百度</a> <a href=http://ir.baidu.com>About Baidu</a> </p> <p id=cp>&copy;2017&nbsp;Baidu&nbsp;<a href=http://www.baidu.com/duty/>使用百度前必读</a>&nbsp; <a href=http://jianyi.baidu.com/ class=cp-feedback>意见反馈</a>&nbsp;京ICP证030173号&nbsp; <img src=//www.baidu.com/img/gs.gif> </p> </div> </div> </div> </body> </html>\r\n'

(2)解析HTML文本

接着使用BeautifulSoup函数,第一个参数是HTML代码,第二个参数是解析器,我们选择“html.parser”:

soup = BeautifulSoup(html,'html.parser') #先生成soup对象,以后用来解析
print(soup.prettify()) #显示格式化

得到结果

<!DOCTYPE html>
<!--STATUS OK-->
<html>
 <head>
  <meta content="text/html;charset=utf-8" http-equiv="content-type"/>
  <meta content="IE=Edge" http-equiv="X-UA-Compatible"/>
  <meta content="always" name="referrer"/>
  <link href="http://s1.bdstatic.com/r/www/cache/bdorz/baidu.min.css" rel="stylesheet" type="text/css"/>
  <title>
   百度一下,你就知道
  </title>
 </head>
 <body link="#0000cc">
  <div id="wrapper">
   <div id="head">
    <div class="head_wrapper">
     <div class="s_form">
      <div class="s_form_wrapper">
       <div id="lg">
        <img height="129" hidefocus="true" src="//www.baidu.com/img/bd_logo1.png" width="270"/>
       </div>
       <form action="//www.baidu.com/s" class="fm" id="form" name="f">
        <input name="bdorz_come" type="hidden" value="1"/>
        <input name="ie" type="hidden" value="utf-8"/>
        <input name="f" type="hidden" value="8"/>
        <input name="rsv_bp" type="hidden" value="1"/>
        <input name="rsv_idx" type="hidden" value="1"/>
        <input name="tn" type="hidden" value="baidu"/>
        <span class="bg s_ipt_wr">
         <input autocomplete="off" autofocus="" class="s_ipt" id="kw" maxlength="255" name="wd" value=""/>
        </span>
        <span class="bg s_btn_wr">
         <input class="bg s_btn" id="su" type="submit" value="百度一下"/>
        </span>
       </form>
      </div>
     </div>
     <div id="u1">
      <a class="mnav" href="http://news.baidu.com" name="tj_trnews">
       新闻
      </a>
      <a class="mnav" href="http://www.hao123.com" name="tj_trhao123">
       hao123
      </a>
      <a class="mnav" href="http://map.baidu.com" name="tj_trmap">
       地图
      </a>
      <a class="mnav" href="http://v.baidu.com" name="tj_trvideo">
       视频
      </a>
      <a class="mnav" href="http://tieba.baidu.com" name="tj_trtieba">
       贴吧
      </a>
      <noscript>
       <a class="lb" href="http://www.baidu.com/bdorz/login.gif?login&amp;tpl=mn&amp;u=http%3A%2F%2Fwww.baidu.com%2f%3fbdorz_come%3d1" name="tj_login">
        登录
       </a>
      </noscript>
      <script>
       document.write('<a href="http://www.baidu.com/bdorz/login.gif?login&tpl=mn&u='+ encodeURIComponent(window.location.href+ (window.location.search === "" ? "?" : "&")+ "bdorz_come=1")+ '" name="tj_login" class="lb">登录</a>');
      </script>
      <a class="bri" href="//www.baidu.com/more/" name="tj_briicon" style="display: block;">
       更多产品
      </a>
     </div>
    </div>
   </div>
   <div id="ftCon">
    <div id="ftConw">
     <p id="lh">
      <a href="http://home.baidu.com">
       关于百度
      </a>
      <a href="http://ir.baidu.com">
       About Baidu
      </a>
     </p>
     <p id="cp">
      ©2017 Baidu
      <a href="http://www.baidu.com/duty/">
       使用百度前必读
      </a>
      <a class="cp-feedback" href="http://jianyi.baidu.com/">
       意见反馈
      </a>
      京ICP证030173号
      <img src="//www.baidu.com/img/gs.gif"/>
     </p>
    </div>
   </div>
  </div>
 </body>
</html>

(3)BeautifulSoup类的基本元素

解析完成以后我们就可以对其进行操作了,现在先来介绍哦一下BeautifulSoup类的基本元素,可以对照着上面解析出来的HTML代码学习:

基本元素说明
Tag标签,最基本的信息组织单元,分别用 <> 和 </> 标明开头和结尾
Name标签的名字,<p>...</p> 的名字是‘p’,格式:.name
Attributes标签的属性,字典形式组织,格式:.attrs
NavigableString标签内非属性字符串,<>…</>中字符串,格式:.string
Comment标签内字符串的注释部分,一种特殊的Comment类型

在这里插入图片描述

接下来演示一下它们的使用:

tag = soup.a #选取a标签
print(tag.attrs) #输出a标签的所有属性
print(tag.attrs['href']) #单独输出a标签的href(链接)属性
print(type(tag.attrs)) #输出a标签属性的类型
print(type(tag)) #输出a标签的类型
print(tag.string) #输出a标签的内容
print(soup.title.string) #输出title标签的内容
print(type(tag.string)) #输出a标签内容的属性

结果如下:

{'href': 'http://news.baidu.com', 'name': 'tj_trnews', 'class': ['mnav']}
http://news.baidu.com
<class 'dict'>
<class 'bs4.element.Tag'>
新闻
百度一下,你就知道
<class 'bs4.element.NavigableString'>

(4)遍历方式

最后介绍一下标签树的遍历,分为三种:下行遍历、上行遍历、平行遍历。
在这里插入图片描述
标签树的下行遍历:

属性说明
.contents子节点的列表,将所以儿子节点存入列表
.children子节点的迭代类型(迭代时使用),与.content类似,用于循环遍历儿子节点
.descendants子孙节点的迭代类型,包含所有的子孙结点,用于循环遍历

下面举例演示用法:

print(soup.head.contents) #输出head节点下的所有儿子节点
print(len(soup.head.contents)) #输出head节点下的儿子节点个数
for child in soup.head.children: #遍历输出head节点下所有儿子节点的名字
    print(child.name)

结果如下:

[<meta content="text/html;charset=utf-8" http-equiv="content-type"/>, <meta content="IE=Edge" http-equiv="X-UA-Compatible"/>, <meta content="always" name="referrer"/>, <link href="http://s1.bdstatic.com/r/www/cache/bdorz/baidu.min.css" rel="stylesheet" type="text/css"/>, <title>百度一下,你就知道</title>]
5
meta
meta
meta
link
title

标签树的上行遍历:

属性说明
.parent父亲的结点标签
.parents结点先辈标签的迭代类型(迭代时使用),用于循环遍历先辈节点

下面举例演示用法:

for parent in soup.a.parents:
    if parent is None:
        print(parent)
    else:
        print(parent.name)

结果如下:

div
div
div
div
body
html
[document]

标签树的平行遍历:

属性说明
.next_sibling返回按照HTML文本顺序的下一个平行节点标签
.prevoius_sibling返回按照HTML文本顺序的上一个平行节点标签
.next_siblings迭代类型,返回按照HTML文本顺序的后续所有平行节点标签
.previous_siblings迭代类型,返回按照HTML文本顺序的前续所有平行节点标签

在这里插入图片描述
下面举例演示用法:

for sibling in soup.a.next_siblings:
        print(sibling)

结果如下:

<a class="mnav" href="http://www.hao123.com" name="tj_trhao123">hao123</a>
 
<a class="mnav" href="http://map.baidu.com" name="tj_trmap">地图</a>
 
<a class="mnav" href="http://v.baidu.com" name="tj_trvideo">视频</a>
 
<a class="mnav" href="http://tieba.baidu.com" name="tj_trtieba">贴吧</a>
 
<noscript> <a class="lb" href="http://www.baidu.com/bdorz/login.gif?login&amp;tpl=mn&amp;u=http%3A%2F%2Fwww.baidu.com%2f%3fbdorz_come%3d1" name="tj_login">登录</a> </noscript>
 
<script>document.write('<a href="http://www.baidu.com/bdorz/login.gif?login&tpl=mn&u='+ encodeURIComponent(window.location.href+ (window.location.search === "" ? "?" : "&")+ "bdorz_come=1")+ '" name="tj_login" class="lb">登录</a>');</script>
 
<a class="bri" href="//www.baidu.com/more/" name="tj_briicon" style="display: block;">更多产品</a>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

比奇堡咻飞兜

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值