Python简易网页爬虫|requests+BeautifulSoup实战
博客导语
爬虫是Python最热门实战方向,本项目带你从零实现简易静态网页爬虫,基于requests 请求库 + BeautifulSoup解析库,实现网页数据抓取、标签解析、文本提取,掌握爬虫核心流程,适合新手入门爬虫领域。
一、技术栈与环境安装
pip install requests beautifulsoup4二、爬虫核心流程
发送网络请求,获取网页源码
解析网页源码,定位目标标签
提取文本、链接等目标数据
打印/保存数据
三、完整实战代码
import requests from bs4 import BeautifulSoup def simple_spider(): # 目标网址(以百度首页为例) url = "https://www.baidu.com" # 请求头,模拟浏览器访问 headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36" } try: # 发送GET请求 res = requests.get(url, headers=headers, timeout=10) res.encoding = "utf-8" print("✅ 网页请求成功,状态码:", res.status_code) # 网页解析 soup = BeautifulSoup(res.text, "html.parser") # 提取网页标题 title = soup.title.string print(f"\n📌 网页标题:{title}") # 提取所有超链接 print("\n📋 页面所有链接:") a_list = soup.find_all("a") for a in a_list: href = a.get("href") text = a.get_text().strip() if href and text: print(f"{text}:{href}") except Exception as e: print("❌ 爬虫请求失败:", e) if __name__ == "__main__": simple_spider()四、核心知识点解析
请求头伪装:添加User-Agent,避免被服务器识别为爬虫拦截
编码设置:手动指定utf-8,解决中文乱码问题
标签解析:find_all批量获取标签,get_text提取文本,get获取属性
异常捕获:防止网络超时、链接失效导致程序崩溃
五、拓展方向
爬取小说、图片、新闻列表数据
新增数据保存到txt/csv文件
增加分页爬取、延时防封禁机制
