Python简易网页爬虫|requests+BeautifulSoup实战

📅 2026/6/24 7:58:19
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, headersheaders, timeout10) 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文件增加分页爬取、延时防封禁机制