Python爬虫实战:定时爬取数据存入SqlServer
Python 爬虫实战:定时爬取数据存入 SqlServer
一、准备工作
1.安装必要的库:
- requests库:用于发送 HTTP 请求获取网页数据,通过pip install requests安装。
- BeautifulSoup库:用于解析 HTML 文档,提取所需数据,使用pip install beautifulsoup4安装。
- schedule库:实现定时任务功能,执行pip install schedule进行安装。
- pyodbc库:用于连接和操作 SqlServer 数据库,可通过pip install pyodbc安装。此外,还需要安装对应版本的 ODBC 驱动程序,以确保能正确连接到 SqlServer 数据库。
2.数据库准备:
- 在 SqlServer 中创建一个数据库和对应的表,用于存储爬取的数据。假设创建了一个名为CrawlerData的数据库,并且在其中创建了一个表WebData,表结构如下:
CREATE TABLE WebData (
id INT IDENTITY(1,1) PRIMARY KEY,
title NVARCHAR(255),
content NVARCHAR(MAX)
);
这里的title和content字段是假设用于存储网页标题和内容的数据列,实际使用时可根据需求调整。
二、编写爬虫代码
1.爬取网页数据:
import requests
from bs4 import BeautifulSoup
def crawl_webpage():
url = "http://www.example.com" # 替换为实际要爬取的网页地址
response = requests.get(url)
if response.status_code == 200:
soup = BeautifulSoup(response.text, 'html.parser')
# 假设提取网页标题和一段内容
title = soup.title.text if soup.title else ""
content = soup.find('p').text if soup.find('p') else ""
return title, content
else:
print(f"请求失败,状态码: {response.status_code}")
return None, None
2.连接 SqlServer 数据库并存储数据:
import pyodbc
def save_to_sqlserver(title, content):
# 连接字符串,根据实际情况修改服务器名、数据库名、用户名和密码
conn_str = 'DRIVER={ODBC Driver 17 for SQL Server};SERVER=your_server_name;DATABASE=CrawlerData;UID=your_username;PWD=your_password'
conn = pyodbc.connect(conn_str)
cursor = conn.cursor()
try:
cursor.execute("INSERT INTO WebData (title, content) VALUES (?,?)", title, content)
conn.commit()
print("数据存储成功")
except Exception as e:
print(f"数据存储失败: {e}")
conn.rollback()
finally:
cursor.close()
conn.close()
三、设置定时任务
import schedule
import time
def main():
# 每小时执行一次爬取和存储任务
schedule.every(1).hours.do(lambda: save_to_sqlserver(*crawl_webpage()))
while True:
schedule.run_pending()
time.sleep(1)
四、运行程序
在 Python 脚本的最后添加以下代码,即可启动定时爬虫任务:
if __name__ == "__main__":
main()
通过以上步骤,就实现了定时爬取网页数据并将其存储到 SqlServer 数据库的功能。在实际应用中,可根据具体需求调整爬取的网页地址、数据提取规则以及定时任务的时间间隔等。同时,还需注意遵守网站的使用规则和相关法律法规,避免造成不必要的法律风险。
更多推荐


所有评论(0)