使用Python实现一个简单的Web爬虫
在当今大数据和人工智能快速发展的时代,数据的获取变得尤为重要。而网络爬虫(Web Crawler)作为自动化收集网页信息的重要工具,广泛应用于搜索引擎、数据分析、市场研究等领域。
本文将介绍如何使用 Python 编写一个简单的 Web 爬虫,抓取指定网站的内容,并从中提取有用的数据。我们将使用 requests
和 BeautifulSoup
这两个常用的库来完成任务。
准备工作
1. 安装必要的库
首先确保你的系统中安装了以下 Python 库:
pip install requests beautifulsoup4 lxml
requests
: 用于发送 HTTP 请求。beautifulsoup4
: 用于解析 HTML 文档。lxml
: 作为 BeautifulSoup 的解析器,速度快且功能强大。基本原理
一个 Web 爬虫的工作流程通常包括以下几个步骤:
发起请求:向目标网站发送 HTTP 请求以获取网页内容。解析响应:将服务器返回的 HTML 内容解析为结构化的数据。提取信息:从解析后的 HTML 中提取所需的数据。存储数据:将提取到的数据保存到文件或数据库中。编写第一个爬虫程序
我们以抓取 https://example.com 页面中的标题(<h1>
标签内容)为例。
示例代码如下:
import requestsfrom bs4 import BeautifulSoupdef fetch_website_title(url): try: # 发起HTTP GET请求 response = requests.get(url) # 判断响应是否成功 if response.status_code == 200: # 使用BeautifulSoup解析HTML内容 soup = BeautifulSoup(response.text, 'lxml') # 提取页面中的<h1>标签内容 title = soup.find('h1').text print(f"页面标题为:{title}") else: print(f"请求失败,状态码:{response.status_code}") except Exception as e: print(f"发生错误:{e}")if __name__ == '__main__': target_url = 'https://example.com' fetch_website_title(target_url)
输出结果:
页面标题为:Example Domain
扩展功能:爬取多个页面并提取多条数据
接下来我们尝试爬取一个测试用的博客网站(例如 https://scrapingclub.com/exercise/list_basic/),并提取所有文章标题。
示例代码如下:
import requestsfrom bs4 import BeautifulSoupdef scrape_blog_titles(base_url): try: response = requests.get(base_url) if response.status_code == 200: soup = BeautifulSoup(response.text, 'lxml') # 找出所有包含文章标题的<div class="card-body"> cards = soup.find_all('div', class_='card-body') for card in cards: title = card.find('h3', class_='card-title').text.strip() price = card.find('h5').text.strip() print(f"标题: {title}, 价格: {price}") else: print(f"请求失败,状态码:{response.status_code}") except Exception as e: print(f"发生错误:{e}")if __name__ == '__main__': blog_url = 'https://scrapingclub.com/exercise/list_basic/' scrape_blog_titles(blog_url)
输出示例:
标题: Short black dress, 价格: $59.99标题: Blue shirt, 价格: $29.99标题: Red pants, 价格: $39.99...
加入分页爬取功能
很多网站会将内容分页展示。我们可以进一步优化上面的爬虫,使其自动爬取所有页面。
def scrape_all_pages(base_url): page_number = 1 while True: url = f"{base_url}?page={page_number}" print(f"正在爬取第 {page_number} 页...") response = requests.get(url) if response.status_code != 200: print("没有更多页面了。") break soup = BeautifulSoup(response.text, 'lxml') cards = soup.find_all('div', class_='card-body') if not cards: print("没有找到任何商品。") break for card in cards: title = card.find('h3', class_='card-title').text.strip() price = card.find('h5').text.strip() print(f"标题: {title}, 价格: {price}") page_number += 1if __name__ == '__main__': base_url = 'https://scrapingclub.com/exercise/list_basic/' scrape_all_pages(base_url)
数据存储:将爬取的数据保存为CSV文件
为了便于后续分析,我们可以将爬取到的数据保存为 CSV 文件。
import csvdef save_to_csv(data, filename='output.csv'): with open(filename, mode='w', newline='', encoding='utf-8') as file: writer = csv.writer(file) writer.writerow(['标题', '价格']) # 写入表头 writer.writerows(data)def scrape_and_save(): base_url = 'https://scrapingclub.com/exercise/list_basic/' all_data = [] page_number = 1 while True: url = f"{base_url}?page={page_number}" print(f"正在爬取第 {page_number} 页...") response = requests.get(url) if response.status_code != 200: print("没有更多页面了。") break soup = BeautifulSoup(response.text, 'lxml') cards = soup.find_all('div', class_='card-body') if not cards: print("没有找到任何商品。") break for card in cards: title = card.find('h3', class_='card-title').text.strip() price = card.find('h5').text.strip() all_data.append([title, price]) page_number += 1 save_to_csv(all_data) print(f"已保存 {len(all_data)} 条数据到 output.csv")if __name__ == '__main__': scrape_and_save()
注意事项与反爬策略
虽然爬虫非常实用,但在实际使用中需要注意以下几点:
遵守 Robots 协议:查看目标网站根目录下的/robots.txt
文件,确认哪些路径允许被爬取。设置请求间隔:频繁请求可能会导致 IP 被封禁,建议添加延迟:import timetime.sleep(1) # 每次请求之间暂停1秒
伪装 User-Agent:有些网站会对非浏览器访问进行限制,可以模拟浏览器行为:headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0 Safari/537.36'}response = requests.get(url, headers=headers)
总结
通过本文的学习,我们掌握了使用 Python 编写简单 Web 爬虫的基本方法,包括:
使用requests
发送 HTTP 请求;使用 BeautifulSoup
解析 HTML;提取页面中的关键信息;实现分页爬取;将数据保存为 CSV 文件;处理基本的反爬机制。当然,真正的工业级爬虫还需要处理 JavaScript 渲染页面(如使用 Selenium 或 Playwright)、分布式爬取、异常重试机制等高级功能。但掌握这些基础知识是迈向专业爬虫工程师的第一步。
如果你对这个方向感兴趣,建议继续学习 Scrapy 框架,它是一个强大的开源爬虫框架,适用于大规模数据采集项目。
参考资料:
Requests 官方文档BeautifulSoup 官方文档Scrapy 官网