本文详细讲解如何利用Python爬虫抓取网页数据并存储到数据库,提供完整源码实现和分步教程。涵盖Requests、BeautifulSoup、Scrapy等技术,以及MySQL和MongoDB数据库操作,适合爬虫初学者和进阶开发者。
一、Python爬虫基础与源码解析
Python爬虫开发主要依赖以下几个核心库:
- Requests:发送HTTP请求获取网页内容
- BeautifulSoup:解析/XML文档
- Scrapy:专业的爬虫框架
基础爬虫示例代码
import requests
from bs4 import BeautifulSoup
url = "https://example.com"
response = requests.get(url)
soup = BeautifulSoup(response.text, '.parser')
print(soup.title.string)
二、数据库连接与存储方案
1. MySQL数据库操作
使用PyMySQL库实现Python与MySQL的交互:
import pymysql
连接数据库
conn = pymysql.connect(host='localhost',
user='root',
password='password',
database='spider_db')
创建数据表
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS articles (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255),
content TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
2. MongoDB存储方案
对于非结构化数据,MongoDB是更好的选择:
from pymongo import MongoClient
client = MongoClient('mongodb://localhost:27017/')
db = client['spider_db']
collection = db['articles']
插入数据
data = {"title": "Python爬虫教程", "content": "..."}
collection.insert_one(data)
三、完整爬虫项目实战
下面是一个完整的新闻网站爬虫示例,包含数据存储功能:
import requests
from bs4 import BeautifulSoup
import pymysql
from datetime import datetime
def crawl_news():
url = "https://news.example.com"
response = requests.get(url)
soup = BeautifulSoup(response.text, '.parser')
连接数据库
conn = pymysql.connect(host='localhost',
user='root',
password='password',
database='news_db')
for item in soup.select('.news-item'):
title = item.select_one('.title').text.strip()
content = item.select_one('.summary').text.strip()
存储到MySQL
with conn.cursor() as cursor:
sql = "INSERT INTO news (title, content, created_at) VALUES (%s, %s, %s)"
cursor.execute(sql, (title, content, datetime.now()))
conn.commit()
conn.close()
四、爬虫优化与反反爬策略
- 设置合理的请求间隔时间
- 使用User-Agent轮换
- 处理Cookie和Session
- 使用代理IP池
- 应对验证码挑战
五、常见问题解答
- Q:爬虫遇到403禁止访问怎么办?
- A:尝试修改请求头信息,特别是User-Agent字段,或使用代理IP。
- Q:如何提高爬虫效率?
- A:可以使用多线程/多进程,或异步框架如aiohttp。
- Q:爬取的数据如何清洗?
- A:使用正则表达式或专门的文本处理库如NLTK进行数据清洗。
通过本教程,您已经掌握了Python爬虫开发的核心技术,从简单的网页抓取到复杂的数据存储。建议从简单的项目开始,逐步增加复杂度,同时注意遵守目标网站的robots.txt协议和相关法律法规。
{3、爬虫
原文链接:https://www.mayiym.com/13089.html,转载请注明出处。