使用Python构建一个简单的Web爬虫
在现代数据驱动的世界中,从互联网上提取信息是一项非常重要的技能。网络爬虫(Web Crawler)或称为网络蜘蛛(Web Spider),是一种自动抓取网页内容的程序。它广泛应用于搜索引擎、数据分析、价格监控等领域。
本文将介绍如何使用 Python 编写一个基本的 Web 爬虫,用于从网页中提取文本内容,并展示如何保存这些数据。我们将使用 requests
和 BeautifulSoup
两个库来实现这个功能。
准备工作
在开始编写代码之前,请确保你已经安装了以下两个 Python 库:
pip install requests beautifulsoup4
requests:用于发送 HTTP 请求并获取网页响应。BeautifulSoup:用于解析 HTML 文档并提取所需的数据。第一步:发送请求获取网页内容
我们首先需要向目标网站发送一个 HTTP GET 请求,获取网页的 HTML 内容。下面是一个使用 requests
获取网页内容的示例:
import requestsdef fetch_webpage(url): try: response = requests.get(url) response.raise_for_status() # 如果响应状态码不是200,抛出异常 return response.text except requests.RequestException as e: print(f"请求失败: {e}") return Noneif __name__ == "__main__": url = "https://example.com" html_content = fetch_webpage(url) if html_content: print("成功获取网页内容!")
注意:请勿对不支持爬虫的网站进行频繁访问,应遵守网站的 robots.txt 文件和相关法律法规。
第二步:解析HTML内容并提取数据
接下来我们使用 BeautifulSoup
来解析 HTML 并提取其中的文本内容。我们可以提取标题、段落等信息。
from bs4 import BeautifulSoupdef extract_text(html_content): soup = BeautifulSoup(html_content, 'html.parser') # 提取标题 title = soup.title.string if soup.title else "无标题" # 提取所有段落 paragraphs = [p.get_text(strip=True) for p in soup.find_all('p')] return { 'title': title, 'paragraphs': paragraphs }if __name__ == "__main__": url = "https://example.com" html_content = fetch_webpage(url) if html_content: data = extract_text(html_content) print(f"标题: {data['title']}") print("段落内容:") for idx, para in enumerate(data['paragraphs'], start=1): print(f"{idx}. {para}")
第三步:保存提取的内容到文件
为了后续分析,我们可以将提取的内容保存为本地文件。这里我们以 .txt
格式保存:
def save_to_file(data, filename="output.txt"): with open(filename, 'w', encoding='utf-8') as f: f.write(f"标题: {data['title']}\n\n") f.write("段落内容:\n") for idx, para in enumerate(data['paragraphs'], start=1): f.write(f"{idx}. {para}\n")if __name__ == "__main__": url = "https://example.com" html_content = fetch_webpage(url) if html_content: data = extract_text(html_content) save_to_file(data) print("内容已保存到 output.txt")
第四步:扩展功能 —— 多页面抓取与链接提取
如果你希望爬取多个页面,可以进一步扩展程序,使其能够从当前页面中提取所有超链接,并递归地访问这些链接。
def extract_links(html_content, base_url): soup = BeautifulSoup(html_content, 'html.parser') links = set() for a_tag in soup.find_all('a', href=True): link = a_tag['href'] # 拼接相对路径 full_link = requests.compat.urljoin(base_url, link) links.add(full_link) return linksif __name__ == "__main__": from collections import deque start_url = "https://example.com" visited = set() queue = deque([start_url]) while queue and len(visited) < 10: # 最多抓取10个页面 current_url = queue.popleft() if current_url in visited: continue print(f"正在抓取: {current_url}") html = fetch_webpage(current_url) if html: data = extract_text(html) save_to_file(data, filename=f"{hash(current_url)}.txt") visited.add(current_url) # 提取链接并加入队列 links = extract_links(html, start_url) for link in links: if link not in visited: queue.append(link)
在这个例子中,我们实现了简单的广度优先搜索(BFS)爬虫,最多抓取10个页面,并将每个页面保存为独立的文件。
高级技巧:使用User-Agent模拟浏览器访问
一些网站会检测 User-Agent 字段来判断是否是爬虫。为了避免被屏蔽,我们可以设置一个常见的浏览器 User-Agent:
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, headers=headers)
总结
通过本文的学习,你应该已经掌握了使用 Python 构建一个简单但功能完整的 Web 爬虫的基本方法。我们介绍了:
如何使用requests
发送 HTTP 请求;如何使用 BeautifulSoup
解析 HTML;如何提取文本内容并保存;如何实现多页面爬取;如何设置 User-Agent 避免被屏蔽。当然,这只是一个基础的入门项目。在实际开发中,你可能还需要考虑更多高级特性,例如:
使用Scrapy
框架构建更复杂的爬虫;使用代理 IP 避免被封禁;对 JavaScript 渲染的页面使用 Selenium
或 Playwright
;数据存储到数据库(如 MySQL、MongoDB);异步爬虫提升效率(使用 aiohttp
+ asyncio
);随着技术的进步,网络爬虫已经成为大数据和人工智能领域不可或缺的一部分。希望这篇文章能为你打开通往自动化数据采集世界的大门!
完整源码地址(可选)
你可以将上述代码整合成一个脚本运行,也可以封装成模块化结构以便复用。
如果你有任何问题,欢迎留言讨论!