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分析其代码结构。

相关推荐
tryCbest9 分钟前
FastAPI中passlib包的作用
python·fastapi·passlib
心中有你021423 分钟前
Python Tkinter 情侣恋爱日记桌面小程序(本地文件存储,无数据库)
开发语言·python
PFFstronger26 分钟前
从 0 到 1 搭建接口自动化测试框架:分层架构 + 数据驱动 + 接口依赖编排
python·架构·自动化
Andya_net30 分钟前
Spring Boot | 条件注解完全指南:从 @Conditional 到 @ConditionalOnExpression 的原理、实践与避坑
spring boot·后端·python
weixin_440730501 小时前
playwright浏览器自动化实战笔记3-登陆以及退出登陆流程-多用户操作
笔记·python·自动化
卷无止境1 小时前
测试全绿,功能能跑,代码却烂到没法上线:AI编程助手留下的十个坑
后端·python
卷无止境1 小时前
终端里的AI战争,命令行编程代理全景扫描
python·agent
SamChan901 小时前
PDF多语言翻译的格式还原技术拆解:从版面分析到内容重排的工程实现
python·ai·pdf·机器翻译
liuze4082 小时前
安装boss-zhipin-mcp(招聘)
开发语言·python
TickDB2 小时前
Python 接入 A 股盘前集合竞价数据:AkShare 报错到 TickDB 实测的完整解法
python·websocket·行情数据 api