使用Python实现一个简单的Web爬虫
在当今数据驱动的时代,网络爬虫(Web Crawler)已成为获取和分析信息的重要工具。本文将介绍如何使用 Python 编写一个简单的 Web 爬虫,从网页中提取数据并进行基本处理。我们将使用 requests
和 BeautifulSoup
这两个流行的库来完成任务。
1. 环境准备
首先,我们需要安装必要的 Python 库:
pip install requests beautifulsoup4
requests
:用于发送 HTTP 请求并获取网页内容。beautifulsoup4
:用于解析 HTML 文档,方便从中提取所需的数据。2. 爬虫的基本原理
Web 爬虫的工作流程通常包括以下几个步骤:
发送 HTTP 请求到目标网站。获取响应中的 HTML 内容。解析 HTML 并提取感兴趣的数据。存储或进一步处理提取的数据。接下来我们将以爬取 https://example.com 上的标题和段落为例进行演示。
3. 编写爬虫代码
以下是一个完整的 Python 脚本,展示了如何实现上述功能:
import requestsfrom bs4 import BeautifulSoupdef fetch_html(url): """ 向指定URL发送GET请求,并返回HTML内容 :param url: 目标网址 :return: HTML文本 """ headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0 Safari/537.36' } try: response = requests.get(url, headers=headers, timeout=10) response.raise_for_status() # 如果状态码不是200,抛出异常 return response.text except requests.RequestException as e: print(f"Error fetching {url}: {e}") return Nonedef parse_html(html_content): """ 解析HTML内容,提取标题和段落 :param html_content: HTML字符串 :return: 包含标题和段落的字典 """ soup = BeautifulSoup(html_content, 'html.parser') title = soup.title.string if soup.title else "No Title Found" paragraphs = [p.get_text(strip=True) for p in soup.find_all('p')] return { 'title': title, 'paragraphs': paragraphs }def main(): url = input("请输入要爬取的网页地址(例如 https://example.com):") html = fetch_html(url) if html: data = parse_html(html) print("\n页面标题:", data['title']) print("\n段落内容:") for i, para in enumerate(data['paragraphs'], start=1): print(f"{i}. {para}")if __name__ == '__main__': main()
3.1 函数说明
fetch_html(url)
此函数使用 requests
向给定 URL 发送 GET 请求,并返回 HTML 响应内容。我们设置了 User-Agent 来模拟浏览器访问,避免被某些网站屏蔽。
parse_html(html_content)
使用 BeautifulSoup
解析 HTML 内容。提取页面标题(<title>
标签)和所有段落(<p>
标签),并将其整理为字典格式返回。
main()
主函数负责接收用户输入的 URL,调用上述两个函数,并打印结果。
4. 示例输出
假设我们运行程序并输入 https://example.com
:
请输入要爬取的网页地址(例如 https://example.com):https://example.com页面标题: Example Domain段落内容:1. More information...
5. 数据存储与扩展
目前我们的爬虫只是将提取的内容打印出来。如果需要长期保存数据,可以将其写入文件或数据库中。例如,我们可以将数据保存为 JSON 文件:
import jsondef save_to_json(data, filename='output.json'): with open(filename, 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=4) print(f"数据已保存至 {filename}")
然后在 main()
中调用该函数:
if html: data = parse_html(html) save_to_json(data) ...
6. 遵守 robots.txt 与反爬机制
在实际部署爬虫时,请务必注意以下几点:
查看目标网站根目录下的robots.txt
文件,确认哪些路径允许爬取。设置合理的请求间隔(如使用 time.sleep()
),避免对服务器造成过大压力。尽量使用合法的 User-Agent 和 Referer 头部,尊重网站的访问策略。若网站有 API 接口,优先使用官方接口获取数据。7. 总结
本文介绍了使用 Python 实现一个简单 Web 爬虫的过程,涵盖了请求发送、HTML 解析、数据提取与保存等核心步骤。通过这个例子,你可以了解如何快速构建自己的爬虫项目,并根据需求进行功能扩展。
随着技术的发展,爬虫不仅可以用来抓取静态网页,还可以处理 JavaScript 渲染的动态页面(使用 Selenium 或 Playwright)。如果你有兴趣深入学习,可以尝试构建更复杂的爬虫系统,比如支持多线程、分布式爬取等。
附录:完整源码
你也可以将以下代码保存为 .py
文件直接运行:
import requestsfrom bs4 import BeautifulSoupimport jsonimport timedef fetch_html(url): headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0 Safari/537.36' } try: response = requests.get(url, headers=headers, timeout=10) response.raise_for_status() return response.text except requests.RequestException as e: print(f"Error fetching {url}: {e}") return Nonedef parse_html(html_content): soup = BeautifulSoup(html_content, 'html.parser') title = soup.title.string if soup.title else "No Title Found" paragraphs = [p.get_text(strip=True) for p in soup.find_all('p')] return { 'title': title, 'paragraphs': paragraphs }def save_to_json(data, filename='output.json'): with open(filename, 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=4) print(f"数据已保存至 {filename}")def main(): url = input("请输入要爬取的网页地址(例如 https://example.com):") html = fetch_html(url) if html: data = parse_html(html) save_to_json(data) print("\n页面标题:", data['title']) print("\n段落内容:") for i, para in enumerate(data['paragraphs'], start=1): print(f"{i}. {para}")if __name__ == '__main__': main()
希望这篇文章对你理解 Web 爬虫有所帮助!如有任何问题,欢迎留言交流。