使用bs4 分析html文件

首先需要 pip install beautifulsoup4安装

然后为了方便学习此插件,随便打开一个网页,然后鼠标右键,打开源网页,如下图片

这样就可以获得一个网页源码,全选复制粘贴到本地,存储为 .html

文件,后续的学习以此html文件为模版进行

python3 复制代码
from bs4 import BeautifulSoup
import os

# html文件放置的路径和名字
filePath = os.path.join(os.getcwd(), "HTML", "1.html")
print(filePath)
# 打开html文件,注意encoding格式
with open(filePath, "r", encoding="UTF-8") as f:
    html_content = f.read()
# 把这个html进行解析
soup = BeautifulSoup(html_content, 'html.parser')

# 这里是抓第一个 <h1>标签的文本内容
h1_content = soup.find('h1').get_text()
# 这里是抓第一个<p> 标签的文本内容
p_content = soup.find('p').get_text()

print('h1 content:', h1_content)
print('p content:', p_content)
print("--------------------------")
# 这里是抓取所有<p> 标签
p_content_all = soup.find_all('p')
# 利用for 循环进行逐条解析,获取文本内容
for p_content in p_content_all:
    print(p_content.get_text())

如,html文件中含结构

html 复制代码
                  <div class="title_box pd10">
                        <h1>六年前的今天:湖人退役科比的8号和24号球衣</h1>
                        <div class="info_box">
                            <span class="time">2023-12-19</span>
                            <span class="source">直播吧</span>
                        </div>
                    </div>

我使用如下命令:

python3 复制代码
# 使用此命令获取 <h1>标签的文本内容
soup.find('h1').get_text()
# 结果:
六年前的今天:湖人退役科比的8号和24号球衣
soup.find('span', class_='time')
# 结果
2023-12-19

例二:

html内容含结构如下:

html 复制代码
                                                    <div class="disZoom bq_bar">
                                                        <div class="disZoom bar_info">
                                                            <span class="biaoqian">
                                                                 <a href="/?cateid=1005" class="tags">体育</a>
                                                            </span>
                                                            <span class="laiyuan">来源:阿希啥都聊</span>
                                                        </div>
                                                    </div>

使用命令:

python3 复制代码
# 抓取html中出现的第一个以下结构内的内容
soup.find('a', herf="/?cateid=1005")
# 结果是:
体育

类似的结构还有:

html 复制代码
                                    </span>
                                        <p class="tit">早报:华为nova 12价格全曝光 蔚来获22亿美元融资</p>
                                    </a>
python3 复制代码
soup.find('p', class_="tit")

基本上你想要抓取的内容都可以按照格式进行解析获取,是非常方便的

先行记录:

在之后自己构建网页后,自主进行管理,获取,导出网页内容应该都是非常有帮助的,避免反复使用re工具自己分析,太过于繁琐,结合 requests 库等,可以更加高效进行网页访问及内容获取。

相关推荐
码路飞29 分钟前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽3 小时前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers
敏编程7 小时前
一天一个Python库:jsonschema - JSON 数据验证利器
python
前端付豪7 小时前
LangChain记忆:通过Memory记住上次的对话细节
人工智能·python·langchain
databook8 小时前
ManimCE v0.20.1 发布:LaTeX 渲染修复与动画稳定性提升
python·动效
花酒锄作田20 小时前
使用 pkgutil 实现动态插件系统
python
前端付豪1 天前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽1 天前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
老赵全栈实战1 天前
Pydantic配置管理最佳实践(一)
python
阿尔的代码屋1 天前
[大模型实战 07] 基于 LlamaIndex ReAct 框架手搓全自动博客监控 Agent
人工智能·python