网络爬虫之Beautifulsoup入门(二)

本文介绍了如何使用BeautifulSoup解析HTML文档,通过示例展示了获取不同标签内容的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. 开启BeautifulSoup之旅
    在使用之前,我们还需要配置解析器,本文及之后都使用python自带的解析器”html.parser”,更多解析器介绍及比较可参考本人博客 Beautiful Soup4 之table数据提取。我们使用一个最常见的例子来说明其使用方法:
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>
"""

使用BeautifulSoup来解析这段代码:

from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc, 'html.parser')

首先引入库函数,接着我们声明一个Beautifulsoup对象soup,括号内的两个参数分别是要解析的代码段、使用的解析器,以后我们还将丰富参数,如在此配置编码等,暂时我们只需要这两个参数即可。接下来仅需对这个对象进行操作即可。

#示例1
soup.title
# <title>The Dormouse's story</title>
#示例2
soup.a
# <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>
#示例3
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>]

以上代码分别是解析代码,获取解析对象的title标签内容、a标签内容、获取所有a标签内容,这就是最简单的应用啦!当然有可能有的小伙伴会疑惑,示例2和示例3都是获取a标签,为什么结果这么大差异呢?这就涉及到对象的种类及相关的属性、操作方法。

2.对象

  • Tag
    Tag 对象与XML或HTML原生文档中的tag相同,其最重要的属性为:name和attributes
  • NavigableString
    Beautiful Soup用 NavigableString 类来包装tag中的字符串,一个 NavigableString 字符串与Python中的Unicode字符串相同。
  • BeautifulSoup
    BeautifulSoup 对象表示的是一个文档的全部内容
  • Comment
    Comment 对象是一个特殊类型的 NavigableString 对象
    更多有关对象的介绍及使用等可在官方文档内获取,本文不做过多总结,用到哪说到哪。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值