python学习笔记--实现简单的爬虫(二)

任务:爬取B站上最爱欢迎的编程课程

网址:编程-哔哩哔哩_bilibili

打开网页的代码模块,如下图:

标题均位于class_="bili-video-card__info--tit"的h3标签中,下面通过代码来实现,需要说明的是URL中的中文写到程序中,已自动转义:

python 复制代码
import requests
from bs4 import BeautifulSoup

url = 'https://search.bilibili.com/all?keyword=%E7%BC%96%E7%A8%8B&from_source=banner_search&order=show&duration=0&tids_1=0'
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
}
# 设置请求头,模拟浏览器访问
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
}

# 发送GET请求
response = requests.get(url, headers=headers)

# 检查请求是否成功
if response.status_code == 200:
    # 解析HTML内容
    soup = BeautifulSoup(response.text, "html.parser")

    # 查找所有<h3>标签
    h3_tags = soup.find_all("h3", class_="bili-video-card__info--tit")

    # 遍历所有<h3>标签,提取title属性值
    for index, h3_tag in enumerate(h3_tags, start=1):
        title = h3_tag.get("title")
        if title:
            print(f"Title {index}: {title}")
        else:
            print(f"Title {index}: 无title属性")
else:
    print("请求失败,状态码:", response.status_code)

输出:

需要注意的是:网页的代码并非一成不变,爬取时一定要使用F12分析其代码结构。

相关推荐
129Lab2 分钟前
BMS算法快速原型开发:AI辅助实现扩展卡尔曼滤波(EKF)SOC估算从理论到代码落地
python·嵌入式开发·bms·卡尔曼滤波·电池管理系统·soc估算
萧鼎6 分钟前
safetensors 库的安装、核心语法与实战用法,安全保存模型权重
python·开源·教程·python库·safetensors
千里码aicood15 分钟前
基于Python语言的测量程序设计
开发语言·python
2601_9623008123 分钟前
用PyTorch Lightning简化空间分析:Python和机器学习的力量
python·深度学习·机器学习·空间分析·pytorchlightning
jayson.h1 小时前
python-可视化提取表格-通用
开发语言·python
悟天特斯2 小时前
AI驱动的楼宇节能:从粗放管控到精准降碳的实践路径
开发语言·人工智能·python·物联网
名字还没想好☜2 小时前
Python 用 tempfile 安全创建临时文件:NamedTemporaryFile、TemporaryDirectory 与别自己拼 /tmp 的坑
开发语言·后端·python·安全·编程语言
北城bot2 小时前
把 Python 脚本打包成 exe
python
萧鼎3 小时前
Python 数据验证神器 Pydantic:数据解析与验证、设置管理、JSONSche、与ORM集成全搞定
开发语言·python
529宝宝起名网3 小时前
用 Python 开发名字字源查询工具:从甲骨文到楷书的字形演变与文化寓意解析
开发语言·python