Python网络爬虫实战

张开发
2026/4/12 22:13:27 15 分钟阅读

分享文章

Python网络爬虫实战
Python网络爬虫实战后端转 Rust 的萌新ID 第一程序员——名字大人很菜暂时。正在跟所有权和生命周期死磕日常记录 Rust 学习路上的踩坑经验和啊哈时刻代码片段保证能跑。保持学习保持输出。欢迎大佬们轻喷也欢迎同好一起进步。前言最近在学习 Python 的过程中我开始关注网络爬虫。作为一个从后端转 Rust 的萌新我认为了解 Python 的网络爬虫技术是非常有必要的它可以帮助我们从互联网上获取数据为后续的分析和应用做准备。Python 提供了多种库和工具来进行网络爬虫如 requests、BeautifulSoup、Scrapy 等。今天我就来分享一下 Python 网络爬虫的相关知识和实战经验希望能帮到和我一样的萌新们。网络爬虫的基本概念什么是网络爬虫网络爬虫Web Crawler是一种自动化程序用于从互联网上获取网页内容。它可以按照一定的规则自动访问网页并提取所需的数据。网络爬虫的应用场景数据采集从网站上获取大量数据信息监控监控网站的更新和变化搜索引擎为搜索引擎抓取网页内容价格比较比较不同网站的商品价格内容聚合聚合多个网站的内容网络爬虫的法律和道德问题遵守 robots.txt网站的 robots.txt 文件规定了爬虫的访问规则控制访问频率避免对网站服务器造成过大压力尊重版权不要侵犯网站的知识产权保护隐私不要采集个人隐私信息网络爬虫的基本流程发送请求向目标网站发送 HTTP 请求获取响应接收网站返回的 HTML 内容解析内容提取所需的数据存储数据将提取的数据存储起来后续处理对数据进行进一步处理和分析常用的网络爬虫库1. requestsrequests是一个简单易用的 HTTP 库用于发送 HTTP 请求。import requests # 发送 GET 请求 response requests.get(https://www.example.com) print(response.status_code) print(response.text) # 发送 POST 请求 data {username: admin, password: 123456} response requests.post(https://www.example.com/login, datadata) print(response.text) # 设置 headers 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 } response requests.get(https://www.example.com, headersheaders) print(response.text)2. BeautifulSoupBeautifulSoup是一个 HTML 和 XML 解析库用于提取网页中的数据。from bs4 import BeautifulSoup import requests # 获取网页内容 response requests.get(https://www.example.com) soup BeautifulSoup(response.text, html.parser) # 提取标题 title soup.title.string print(title) # 提取所有链接 links soup.find_all(a) for link in links: print(link.get(href)) # 提取特定类的元素 items soup.find_all(class_item) for item in items: print(item.text)3. ScrapyScrapy是一个功能强大的网络爬虫框架用于大规模的数据采集。import scrapy class ExampleSpider(scrapy.Spider): name example start_urls [https://www.example.com] def parse(self, response): # 提取标题 title response.css(title::text).get() yield {title: title} # 提取链接 links response.css(a::attr(href)).getall() for link in links: yield {link: link}实战案例爬取 GitHub trending 页面1. 分析页面结构首先我们需要分析 GitHub trending 页面的结构确定需要提取的数据和提取方法。2. 编写爬虫代码import requests from bs4 import BeautifulSoup # 发送请求 url https://github.com/trending 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 } response requests.get(url, headersheaders) # 解析内容 soup BeautifulSoup(response.text, html.parser) # 提取项目信息 projects [] for project in soup.find_all(article, class_Box-row): # 提取项目名称 name project.find(h2, class_h3 lh-condensed).text.strip().replace(\n, ).replace( , ) # 提取项目描述 description project.find(p, class_col-9 text-gray my-1 pr-4) description description.text.strip() if description else # 提取语言 language project.find(span, class_text-gray-dark mr-3) language language.text.strip() if language else # 提取 stars stars project.find(a, class_Link--muted d-inline-block mr-3).text.strip() # 提取 forks forks project.find_all(a, class_Link--muted d-inline-block mr-3) forks forks[1].text.strip() if len(forks) 1 else # 提取今日 stars today_stars project.find(span, class_d-inline-block float-sm-right) today_stars today_stars.text.strip() if today_stars else projects.append({ name: name, description: description, language: language, stars: stars, forks: forks, today_stars: today_stars }) # 打印结果 for project in projects: print(fName: {project[name]}) print(fDescription: {project[description]}) print(fLanguage: {project[language]}) print(fStars: {project[stars]}) print(fForks: {project[forks]}) print(fToday Stars: {project[today_stars]}) print(- * 50)3. 存储数据import csv # 存储为 CSV 文件 with open(github_trending.csv, w, newline, encodingutf-8) as f: writer csv.writer(f) writer.writerow([Name, Description, Language, Stars, Forks, Today Stars]) for project in projects: writer.writerow([ project[name], project[description], project[language], project[stars], project[forks], project[today_stars] ]) print(数据已存储到 github_trending.csv)网络爬虫的最佳实践1. 设置合理的请求头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, Accept: text/html,application/xhtmlxml,application/xml;q0.9,*/*;q0.8, Accept-Language: en-US,en;q0.5, Accept-Encoding: gzip, deflate, Connection: keep-alive, Upgrade-Insecure-Requests: 1 }2. 控制访问频率import time for url in urls: response requests.get(url, headersheaders) # 处理响应 time.sleep(1) # 暂停 1 秒3. 使用代理proxies { http: http://127.0.0.1:7890, https: http://127.0.0.1:7890 } response requests.get(url, headersheaders, proxiesproxies)4. 处理异常try: response requests.get(url, headersheaders, timeout10) response.raise_for_status() # 检查状态码 except requests.exceptions.RequestException as e: print(fError: {e})5. 使用会话管理session requests.Session() session.headers.update(headers) # 登录 data {username: admin, password: 123456} session.post(https://www.example.com/login, datadata) # 访问需要登录的页面 response session.get(https://www.example.com/dashboard)常见问题与解决方案1. 网站反爬措施问题网站采取了反爬措施如 IP 封锁、验证码等。解决方案使用代理 IP控制访问频率使用会话管理模拟浏览器行为处理验证码使用 OCR 或人工识别2. 动态内容问题网站使用 JavaScript 动态加载内容直接爬取无法获取完整数据。解决方案使用 Selenium 模拟浏览器分析 API 请求使用 Pyppeteer 或 Playwright3. 数据提取困难问题网页结构复杂数据提取困难。解决方案使用 XPath 或 CSS 选择器利用正则表达式分析网页结构找到规律4. 数据存储问题问题爬取的数据量大存储困难。解决方案使用数据库存储分批处理数据使用流式处理5. 爬虫被封锁问题爬虫被网站封锁无法继续爬取。解决方案更换 IP 地址更改请求头调整爬取策略遵守网站的 robots.txt 规则总结Python 网络爬虫是一种强大的数据采集工具它可以帮助我们从互联网上获取大量数据。通过本文的学习我们了解了网络爬虫的基本概念、应用场景、法律和道德问题、基本流程、常用库、实战案例、最佳实践和常见问题与解决方案。作为一个从后端转 Rust 的萌新我认为学习 Python 的网络爬虫技术是非常有价值的。它不仅可以帮助我们获取数据还可以让我们更好地理解网络协议和网页结构。在使用网络爬虫时我们应该遵守法律和道德规范尊重网站的权益同时采取适当的措施来应对反爬策略。通过不断学习和实践我们可以开发出更加高效、可靠的网络爬虫。保持学习保持输出今天的 Python 网络爬虫实战文章就到这里希望对大家有所帮助。欢迎在评论区分享你的经验和问题我们一起进步

更多文章