【python爬虫专项(4)】BeautifulSoup介绍、安装以及简单使用

1. BeautifulSoup介绍与安装

1.1 什么是BeautifulSoup

Beautiful Soup 是一个可以从HTML或XML文件中提取数据的Python库.它能够通过转换器实现惯用的文档导航,查找,修改文档的方式

1.2 如何安装?

首先查看电脑中有没有BeautifulSoup工具包:pip show beautifulsoup4
在这里插入图片描述
直接安装:pip install beautifulsoup4

1.3 如何导入BeaitufulSoup?

在代码窗口顶部输入: from bs4 import BeautifulSoup

1.4 官方案例演示

设置变量,输入以下html内容​,代码如下

h = """
<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>
"""


soup = BeautifulSoup(h,'lxml')

print(soup)#直接输出
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>

解析标签

查找title标签soup.title
输出title标签的名字soup.title.name
查找p标签soup.p
输出p标签中属性class的内容soup.p[‘class’]
查找a标签soup.a/soup.find(‘a’)
查找所有a标签soup.find_all(‘a’)

查找title标签

print(soup.title)

#输出为:
<title>The Dormouse's story</title>

输出title标签的名字

print(soup.title.name)

#输出为:
'tltle'

查找p标签

print(soup.p)

#输出为
<p class="title"><b>The Dormouse's story</b></p>

输出p标签中属性class的内容

print(soup.p['class'])

#输出为
['title']

查找a标签

print(soup.a)
print(soup.find('a'))

#输出为
<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>
<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>

查找所有a标签

print(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>]

直接使用soup.tag(标签)的输出结果和使用soup.find(‘tag’)的输出结果是一样的,而且都是 <class ‘bs4.element.Tag’>数据类型

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

lys_828

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

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

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

打赏作者

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

抵扣说明:

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

余额充值