天猫拿到的数据存入到sqlite中

import re
import sqlite3
import requests
import json
import os

path = './bra.sqlite'

if os.path.exists(path):
    os.remove(path)

create_sql = '''
    create table sales(
    id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
    color TEXT NOT NULL ,
    size TEXT NOT NULL ,
    source TEXT NOT NULL ,
    comment TEXT NOT NULL ,
    data  TEXT NOT NULL
    );
'''

##如果没有数据库就创建,如果有就连接数据库
conn = sqlite3.connect(path)

# 执行sql语句   """ Return a cursor for the connection. """
cursor = conn.cursor()

# 执行建表动作,   execute: 增加,删除,修改,提交事务    """ Executes a SQL statement. """
cursor.execute(create_sql)

conn.commit() 


# 某一个商品的,某一页的数据
def get_rateDetail(itemId, currentPage):
    try:
        url = "https://rate.tmall.com/list_detail_rate.htm?itemId=" + str(
            itemId) + "&spuId=687158212&sellerId=2917184910&order=3&currentPage=" + str(
            currentPage) + "&append=0&content=1&tagId=&posi=&picture=&ua=098%23E1hvHvvLvxZvUpCkvvvvvjiPPsdygjrbRLc9zjnEPmPh1jnjPLqUgj3nRFqp6jnmROhCvCB476czVr147DdE2KNGTDuM7K2No86CvvDvpLGp5pCvbagtvpvhphvvvUhCvCn37ejSDY147Du8jrYUAwFRSG3qRphvChCvvvvCvpvVphhvvvvvKphv8hCvvvvvvhCvphvZ7pvvp%2BnvpCBXvvC2p6CvHHyvvh89phvZ7pvvpumEvpvVpyUUCC%2BwuphvmhCvCEcrhGO9mphvLhUTN9mFdeZvVAdhaB4AVAi1bPoxdX3Qb7gnIOZtIoYbE7LBIb8rwZ9anbmxdX3Qbc6OfwoOdexBfvDr08TJEct1pc7QrEtlp7Q4S4ZPvpvhvv2MMTwCvvBvpvpZ3QhvChCCvvmrvpvBohyf2jOvphep05lB%2B2hmOs8rvpvEphVk28pvpjn5dphvHhrE6C2bvhv26i3YmLeQbyICaajECQhvCli4zYMwEfGtvpvhphvvv2yCvvBvpvvv&needFold=0&_ksTS=1536980088890_1373&callback=jsonp1374"

        # 请求
        response = requests.get(url)

        # JSON类型的str数据
        data = response.text.replace("jsonp1374(",   "").replace(")",    "")

        data_dict = json.loads(data, encoding="utf-8")

        rateDetail = data_dict["rateDetail"]

        # 总页数
        total_page = rateDetail["paginator"]["lastPage"]

        print("itemId===", itemId, "currentPage==", currentPage, "总页数==", total_page)

        # 得到当前评论也的胸罩的颜色,尺寸   
        for item in rateDetail["rateList"]:
            try:
                print("-----------------------------------")
                auctionSku = item["auctionSku"]
                auctionSku = re.split(r'[:;]', auctionSku)
                color = auctionSku[1]
                size = auctionSku[3]
                content = item["rateContent"]
                # 评论的时间
                rate_date = item["rateDate"]


                # 插入数据到表中
                insert_sql = "INSERT INTO sales(color,size,source,comment,data) VALUES('%s','%s','%s','%s','%s')" % (
                    color, size, "天猫", content, rate_date)
                print("insert_sql==", insert_sql)
                # 执行sql    """ Executes a SQL statement. """
                cursor.execute(insert_sql)
                # 提交事务      """ Commit the current transaction. """
                conn.commit()


            except Exception as e:
                print("出错了==", e, "item==", item)

    except Exception as e:
        print("出错了===", e, "url===", url)


if __name__ == "__main__":
    for page in range(1, 100):
        get_rateDetail(547746378793, page)

建数据库,表

path = './bra.sqlite'

if os.path.exists(path):
    os.remove(path)

create_sql = '''
    create table sales(
    id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
    color TEXT NOT NULL ,
    size TEXT NOT NULL ,
    source TEXT NOT NULL ,
    comment TEXT NOT NULL ,
    data  TEXT NOT NULL
    );
'''

##如果没有数据库就创建,如果有就连接数据库
conn = sqlite3.connect(path)

# 执行sql语句   """ Return a cursor for the connection. """
cursor = conn.cursor()

# 执行建表动作,   execute: 增加,删除,修改,提交事务    """ Executes a SQL statement. """
cursor.execute(create_sql)

conn.commit() 

数据入表


                # 插入数据到表中
                insert_sql = "INSERT INTO sales(color,size,source,comment,data) VALUES('%s','%s','%s','%s','%s')" % (
                    color, size, "天猫", content, rate_date)
                print("insert_sql==", insert_sql)
                # 执行sql    """ Executes a SQL statement. """
                cursor.execute(insert_sql)
                # 提交事务      """ Commit the current transaction. """
                conn.commit()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用Python内置的sqlite3模块来将数据存入SQLite数据。步骤如下: 1. 导入sqlite3模块 ```python import sqlite3 ``` 2. 连接到SQLite数据库 ```python conn = sqlite3.connect('example.db') ``` 其,`example.db`是数据库文件名,如果该文件不存在,则会自动创建。 3. 创建表格 ```python conn.execute('''CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, age INTEGER NOT NULL);''') ``` 该语句创建了一个名为`users`的表格,包含三个字段:`id`、`name`和`age`。 4. 插入数据 ```python conn.execute("INSERT INTO users (name, age) VALUES (?, ?)", ('John', 25)) ``` 该语句插入了一条数据,将`name`设置为`John`,`age`设置为`25`。 5. 查询数据 ```python cursor = conn.execute("SELECT * FROM users") for row in cursor: print("ID = ", row[0]) print("Name = ", row[1]) print("Age = ", row[2]) ``` 该语句查询了`users`表格的所有数据,并依次打印出每条数据的`id`、`name`和`age`字段。 6. 关闭连接 ```python conn.close() ``` 完整代码如下: ```python import sqlite3 # 连接到SQLite数据库 conn = sqlite3.connect('example.db') # 创建表格 conn.execute('''CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, age INTEGER NOT NULL);''') # 插入数据 conn.execute("INSERT INTO users (name, age) VALUES (?, ?)", ('John', 25)) # 查询数据 cursor = conn.execute("SELECT * FROM users") for row in cursor: print("ID = ", row[0]) print("Name = ", row[1]) print("Age = ", row[2]) # 关闭连接 conn.close() ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值