当前位置: 首页 > news >正文

Python 网页解析初级篇:BeautifulSoup库的入门使用

在Python的网络爬虫中,网页解析是一项重要的技术。而在众多的网页解析库中,BeautifulSoup库凭借其简单易用而广受欢迎。在本篇文章中,我们将学习BeautifulSoup库的基本用法。

一、BeautifulSoup的安装与基本使用

首先,我们需要使用pip命令来安装BeautifulSoup库,命令如下:

pip install beautifulsoup4

安装完成后,我们就可以开始使用BeautifulSoup来解析网页了。首先,我们需要导入BeautifulSoup类,然后使用BeautifulSoup类的构造方法创建一个BeautifulSoup对象,代码如下:

from bs4 import BeautifulSouphtml_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>
"""soup = BeautifulSoup(html_doc, 'html.parser')print(soup.prettify())

二、网页元素的提取

BeautifulSoup提供了一系列方法,让我们可以轻松的提取出网页中的元素。例如,我们可以使用tag.name属性获取标签的名字,tag.string属性获取标签内的字符串,使用tag['attr']获取标签的属性,代码如下:

from bs4 import BeautifulSouphtml_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>
"""soup = BeautifulSoup(html_doc, 'html.parser')title_tag = soup.titleprint(title_tag.name)  # 输出:title
print(title_tag.string)  # 输出:The Dormouse's story

三、网页元素的查找

BeautifulSoup提供了findfind_all方法,让我们可以轻松的查找到网页中的元素。例如,我们可以查找到所有的p标签,代码如下:

from bs4 import BeautifulSouphtml_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</p>
"""soup = BeautifulSoup(html_doc, 'html.parser')p_tags = soup.find_all('p')for p in p_tags:print(p.string)

四、CSS选择器的使用

BeautifulSoup还支持CSS选择器,我们可以使用select方法来使用CSS选择器选择元素,例如:

from bs4 import BeautifulSouphtml_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</p>
"""soup = BeautifulSoup(html_doc, 'html.parser')title_tag = soup.select('p.title')for title in title_tag:print(title.string)

以上就是BeautifulSoup库的基本用法,通过BeautifulSoup,我们可以轻松地解析出网页中的元素,为网络爬虫提供强大的支持。

http://www.lryc.cn/news/134359.html

相关文章:

  • Spring Schedular 定时任务
  • 营业额统计
  • 使用lodash的throttle函数会触发两次
  • 如何使用CSS实现一个瀑布流布局?
  • dfs之有重复字符串的排列组合
  • Java之抽象类
  • “无Internet连接但是可以上网” 解决全流程
  • VS2022 CMake报错解决小结
  • java之webservice_aegis.xml学习
  • 总结 TCP 协议的相关特性
  • 不负众望~历时4年修炼,这本册子终于成书了(文末赠书)
  • 【校招VIP】java语言考点之垃圾回收算法
  • juc概述和Lock接口
  • 图像降采样的计算原理:F.interpolate INTER_AREA
  • 云上的甜蜜早安:腾讯云云函数助力PHP打造女友专属每日推送
  • Javaweb基础学习(3)
  • 使用在 Web 浏览器中运行的 VSCode 实现 ROS2 测程法
  • 快速学习GO语言总结
  • 尚硅谷宋红康MySQL笔记 10-18
  • Java 面试题--SpringBoot篇
  • GitKraken 详细图文教程
  • ubuntu20.04 root用户下使用中文输入法——root用户pycharm无法用中文输入法问题
  • FastDFS与Nginx结合搭建文件服务器,并实现公网访问【内网穿透】
  • 嵌入式蓝海变红海?其实是大浪淘沙!
  • 【附安装包】Solid Edge2023安装教程最强CAD选择
  • 494. 目标和
  • C++学习笔记总结练习:C++编译过程详解
  • 嵌入式设备应用开发(qt界面开发)
  • pytest结合Excel实现接口自动化
  • 【LLM数据篇】预训练数据集+指令生成sft数据集