将爬取的数据存储到数据库

本文介绍如何使用Python的pymysql库将爬取的数据存储到MySQL数据库中。通过创建数据库连接、游标对象及执行SQL语句,将数据插入到预设的userInfo表中。示例代码包含异常处理,确保数据安全存储。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

之前都是将数据存到了文档中或者excel中(排版很不好,稍后研究一下),今天尝试一下对数据库的操作……

先上代码吧:

class Mysql_Exe():
    def _getconn(self):
        try:
            self.conn=pymysql.connect(host='127.0.0.1',user='root',passwd='123456',port=3306,db='mysql',charset='utf8')
        except pymysql.Error as e:
            print(e,'数据库连接失败')
    def _closeconn(self):
        try:
            if self.conn:
                self.conn.close()
        except pymysql.Error as e:
                print(e,'关闭数据库连接失败')
    def insertData(self,item):
        sql='insert into userInfo value(%s,%s,%s)'
        try:
            self._getconn()
            cursor=self.conn.cursor() #获取cursor对象
            cursor.execute(sql,(item[0],item[1],item[2])) #预处理并执行数据库操作
            self.conn.commit() #
爬取数据存储数据库中通常包括以下几个步骤: 1. **选择数据库**:首先需要选择合适的数据库类型。常见的选择包括关系型数据库(如MySQL、PostgreSQL)和非关系型数据库(如MongoDB)。 2. **安装数据库**:根据选择的数据库类型,进行相应的安装和配置。例如,安装MySQL可以使用包管理器(如`apt`或`yum`),或者下载安装包进行安装。 3. **设计数据库结构**:根据爬取数据类型,设计数据库的表结构。确定需要存储的字段及其数据类型。 4. **编写爬虫代码**:使用编程语言(如Python)和爬虫框架(如Scrapy、BeautifulSoup)编写爬虫代码,获取所需的数据。 5. **连接数据库**:在爬虫代码中,添加数据库连接代码。可以使用相应的数据库驱动库(如`pymysql`用于MySQL,`psycopg2`用于PostgreSQL,`pymongo`用于MongoDB)。 6. **存储数据**:将爬取数据通过SQL语句或ORM框架(如SQLAlchemy)插入到数据库中。 以下是一个使用Python和MySQL存储爬取数据的示例代码: ```python import pymysql from bs4 import BeautifulSoup import requests # 数据库连接配置 db_config = { 'host': 'localhost', 'user': 'your_username', 'password': 'your_password', 'db': 'your_database', 'charset': 'utf8mb4' } # 爬虫代码 def fetch_data(url): response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser') data = [] for item in soup.find_all('div', class_='item'): title = item.find('h2').text description = item.find('p').text data.append((title, description)) return data # 存储数据数据库 def store_data(data): connection = pymysql.connect(**db_config) try: with connection.cursor() as cursor: sql = "INSERT INTO items (title, description) VALUES (%s, %s)" cursor.executemany(sql, data) connection.commit() finally: connection.close() # 主程序 if __name__ == "__main__": url = 'http://example.com' scraped_data = fetch_data(url) store_data(scraped_data) ``` 在这个示例中,我们使用`requests`库获取网页内容,使用`BeautifulSoup`解析HTML,然后提取所需的数据。最后,使用`pymysql`库将数据插入到MySQL数据库中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

beyond_LH

您的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值