Python爬虫入库操作包括:建立数据库连接;准备SQL插入语句;执行插入操作;提交事务;关闭连接。

Python 爬虫入库操作教程
引言
Python爬虫入库是指将爬取到的数据保存到数据库(如MySQL、MongoDB)中。这一步骤对于数据分析、机器学习和数据可视化等任务至关重要。本教程将分步介绍如何使用Python爬虫将数据入库。
数据库设置
立即学习“Python免费学习笔记(深入)”;
Python 爬虫设置
入库操作
1. 建立数据库连接
<code class="python">import mysql.connector as mysql
db = mysql.connect(
host="localhost",
user="root",
password="rootpassword", # 替换为您的密码
database="my_database",
)
cursor = db.cursor()</code>2. 准备 SQL 插入语句
<code class="python">sql = "INSERT INTO my_table (field1, field2, field3) VALUES (%s, %s, %s)"</code>
3. 执行插入操作
<code class="python">data = ("value1", "value2", "value3")
cursor.execute(sql, data)</code>4. 提交事务
<code class="python">db.commit()</code>
5. 关闭连接
<code class="python">cursor.close() db.close()</code>
示例
以下是使用BeautifulSoup和Requests爬取网页数据并存入MySQL数据库的示例代码:
<code class="python">import requests
from bs4 import BeautifulSoup
import mysql.connector as mysql
# 爬取网页数据
url = "example.com"
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")
# 提取数据并准备 SQL 插入语句
sql = "INSERT INTO my_table (title, content) VALUES (%s, %s)"
data = []
for article in soup.find_all("article"):
title = article.find("h1").text
content = article.find("p").text
data.append((title, content))
# 建立数据库连接并执行插入操作
db = mysql.connect(...) # 同上
cursor = db.cursor()
cursor.executemany(sql, data)
db.commit()
# 关闭连接
cursor.close()
db.close()</code>以上就是python爬虫入库操作教程的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号