Python进阶教程:网络编程与数据抓取

发布时间:2026/8/17 19:42:04
Python进阶教程:网络编程与数据抓取 目录Python进阶教程网络编程与数据抓取一、HTTP 基础二、urllib标准库 HTTP 客户端三、requests更优雅的 HTTP 库四、HTML 解析BeautifulSoup五、实战抓取网页文章标题六、爬虫的注意事项七、进阶接口调用API总结Python进阶教程网络编程与数据抓取本文是Python 入门教程系列的第 5 篇。前面四篇介绍了基础语法、OOP、文件操作、常用标准库本篇介绍网络编程与数据抓取爬虫基础。一、HTTP 基础网络编程的核心是 HTTP 协议。HTTP 请求主要由四部分组成方法GET获取、POST提交、PUT、DELETE 等URL资源地址请求头User-Agent、Cookie、Content-Type 等请求体POST 时携带的数据响应同样包含状态码200 成功、404 不存在、500 服务器错误、响应头和响应体。二、urllib标准库 HTTP 客户端importurllib.requestimporturllib.parse# GET 请求urlhttps://httpbin.org/getrequrllib.request.Request(url,headers{User-Agent:Mozilla/5.0})withurllib.request.urlopen(req,timeout10)asresp:print(resp.status)# 200print(resp.read().decode(utf-8)[:200])# POST 请求dataurllib.parse.urlencode({name:Alice,age:20}).encode()requrllib.request.Request(https://httpbin.org/post,datadata)withurllib.request.urlopen(req)asresp:print(resp.read().decode(utf-8)[:200])三、requests更优雅的 HTTP 库requests 是第三方库pip install requests是实际开发中的首选importrequests# GET 请求resprequests.get(https://httpbin.org/get,params{q:python},timeout10)print(resp.status_code)# 200print(resp.json())# 自动解析 JSON# POST 请求resprequests.post(https://httpbin.org/post,json{name:Alice})print(resp.json())# 自定义请求头模拟浏览器headers{User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64)}resprequests.get(https://httpbin.org/headers,headersheaders)# 下载文件resprequests.get(https://httpbin.org/image/png,streamTrue)withopen(image.png,wb)asf:forchunkinresp.iter_content(chunk_size8192):f.write(chunk)四、HTML 解析BeautifulSoup抓取网页后需要解析 HTMLBeautifulSoup 是最常用的工具pip install beautifulsoup4frombs4importBeautifulSoupimportrequests html htmlbody h1Python 教程/h1 div classarticle a href/p1第一篇/a a href/p2第二篇/a /div /body/html soupBeautifulSoup(html,html.parser)# 获取标题print(soup.h1.text)# Python 教程# 按 class 查找divsoup.find(div,class_article)# 查找所有链接foraindiv.find_all(a):print(a.text,a[href])# 第一篇 /p1# 第二篇 /p2五、实战抓取网页文章标题综合运用以上知识写一个抓取网页所有链接和标题的小工具importrequestsfrombs4importBeautifulSoupdeffetch_links(url):抓取页面中所有链接及其文本try:headers{User-Agent:Mozilla/5.0}resprequests.get(url,headersheaders,timeout10)resp.raise_for_status()# 非 200 会抛出异常soupBeautifulSoup(resp.text,html.parser)links[]forainsoup.find_all(a,hrefTrue):texta.text.strip()or(无文本)links.append((text[:30],a[href]))returnlinksexceptrequests.RequestExceptionase:print(f请求失败{e})return[]# 使用示例urlhttps://example.comfortext,hrefinfetch_links(url)[:10]:print(f{text}-{href})六、爬虫的注意事项合法、规范的爬虫需要注意遵守 robots.txt访问站点前检查https://站点/robots.txt了解允许爬取的内容。控制请求频率用 time.sleep 间隔请求避免给服务器造成压力。设置合理 UA识别为真实浏览器但不要伪装成他人。尊重版权只抓取允许的数据注意使用条款。反爬处理遇到验证码、登录墙时不要强行绕过。importtimeimportrequests urls[https://httpbin.org/get]*5forurlinurls:resprequests.get(url,timeout10)print(resp.status_code)time.sleep(2)# 每 2 秒请求一次礼貌抓取七、进阶接口调用API现代开发更多是调用 API 获取 JSON 数据配合上篇的 json 库非常方便importrequestsimportjsondefcall_api(url,paramsNone):resprequests.get(url,paramsparams,timeout10)ifresp.status_code200:returnresp.json()else:print(fAPI 返回错误{resp.status_code})returnNone# 调用公开 API 获取天气信息示例datacall_api(https://httpbin.org/json)ifdata:print(json.dumps(data,ensure_asciiFalse,indent2))总结本篇介绍了 HTTP 基础、urllib 与 requests 两种 HTTP 客户端、BeautifulSoup 网页解析、以及爬虫的规范与注意事项并提供了两个实战工具。下一篇将介绍多线程与多进程敬请期待