首页 > 数据库 >Day 20 20.3 数据库之Python操作MySQL

Day 20 20.3 数据库之Python操作MySQL

时间:2023-04-02 20:37:16浏览次数:39  
标签:20.3 20 get Python res self cursor book def

Python操作MySQL

import pymysql

# 打开数据库连接

db = pymysql.connect(host='localhost', user='root', passwd='...', port=3306,datebase='...')
print('连接成功!')

# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()

# 使用 execute()  方法执行 SQL 查询
cursor.execute("SELECT VERSION()")

# 使用 fetchone() 方法获取单条数据.
data = cursor.fetchone()

print("Database version : %s " % data)

# 关闭数据库连接
db.close()

class版本

import pymysql


class DBHandler:
    def __init__(self, host, port, user, password,
                 database, charset, **kwargs):
        # 连接数据库服务器
        self.conn = pymysql.connect(host=host, port=port, user=user, password=password,
                                    database=database, cursorclass=pymysql.cursors.DictCursor,
                                    charset=charset, **kwargs)
        # 获取游标
        self.cursor = self.conn.cursor()

    def query(self, sql, args=None, one=True):
        self.cursor.execute(sql, args)
        if one:
            return self.cursor.fetchone()
        else:
            return self.cursor.fetchall()

    def close(self):
        self.cursor.close()
        self.conn.close()


if __name__ == "__main__":
    db = DBHandler(host='127.0.0.1', port=3306,
                   user='root', password='....',
                   database='uric', charset='utf8')
    sql = 'SELECT VERSION()'
    data = db.query(sql)
    print(data)

爬虫小说存储案例

import requests
from lxml import etree
import pymysql


class Spider(object):
    def __init__(self, host, port, user, password,
                 database, charset, **kwargs):
        # 连接数据库服务器
        self.conn = pymysql.connect(host=host, port=port, user=user, password=password,
                                    database=database, cursorclass=pymysql.cursors.DictCursor,
                                    charset=charset, **kwargs)
        # 获取游标
        self.cursor = self.conn.cursor()

        # 初始化表、
        self.init_table()

        self.headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36',
        }

        self.session = requests.session()

    def exec(self, sql, args=None, one=True):
        self.cursor.execute(sql, args)
        self.conn.commit()

        if one:
            return self.cursor.fetchone()
        else:
            return self.cursor.fetchall()

    def close(self):
        self.cursor.close()
        self.conn.close()

    def init_table(self):

        # 使用 execute()  方法执行 SQL 查询
        sql1 = """
           create table if not exists book(
           id int primary key auto_increment,
           bookName varchar(32),
           coverImg varchar(255),
           authorPenName varchar(32)
           )character set=utf8; 
           """
        self.exec(sql1)

        sql2 = """
               create table if not exists chapter(
               id int primary key auto_increment ,
               chapter_name varchar(32),
               chapter_content text,
               book_id INT NOT NULL
               )character set=utf8;
               """
        self.exec(sql2)

    def login(self):
        self.session.post("https://passport.17k.com/ck/user/login", data={
            "loginName": ".....",
            "password": "...."
        }, headers=self.headers)

    def get_shelf_books(self):
        '''
        params:
        :return: data [{},{},{}]
        '''
        res = self.session.get("https://user.17k.com/ck/author/shelf?page=1&appKey=2406394919")

        res.encoding = "utf8"
        # print(res.text)
        data = res.json().get("data")

        for book_dict in data:
            self.handle_one_book(book_dict)

    def handle_one_book(self, book_dict):
        # 循环处理每一本书
        print(book_dict)
        bookId = book_dict.get("bookId")
        bookName = book_dict.get("bookName")
        coverImg = book_dict.get("coverImg")
        authorPenName = book_dict.get("authorPenName")

        sql = f"""insert into book (bookName,coverImg,authorPenName) values (
            "{bookName}","{coverImg}","{authorPenName}");"""
        print("sql:::", sql)
        self.exec(sql)

        # 爬取每一章的文本信息并下载
        self.get_chapters(bookId)

    def get_chapters(self, book_id):

        # 爬虫每一本书架书籍的章节页面
        res = requests.get(f"https://www.17k.com/list/{book_id}.html")
        res.encoding = "utf8"
        # 解析该书籍的章节页面中章节链接
        selector = etree.HTML(res.text)
        items = selector.xpath('//dl[@class="Volume"][position()>1]/dd/a')

        for item in items:
            self.handle_one_chapter(item, book_id)

    def handle_one_chapter(self, item, book_id):
        # 每一本书籍的每一章节的信息
        chapter_href = item.xpath("./@href")[0]
        chapter_name = item.xpath("./span/text()")[0].strip()
        # 爬取章节内容
        res = requests.get("https://www.17k.com" + chapter_href)
        res.encoding = "utf8"
        chapter_html = res.text
        print(chapter_html)
        selector = etree.HTML(res.text)
        chapter_content_list = selector.xpath(
            '//div[contains(@class,"content")]/div[@class="p"]/p[position()<last()]/text()')
        chapter_content_str = "\n".join(chapter_content_list)
        # 章节进行下载,写入到一个文件中

        sql = f"""insert into chapter (chapter_name,chapter_content,book_id) values (
                  "{chapter_name}",'{chapter_content_str}',"{book_id}");"""
        print("sql:::", sql)
        self.exec(sql)

    def run(self):
        # (1) 模拟登录,获取Cookie
        self.login()
        # (2) 爬取书架上的书籍信息
        self.get_shelf_books()


if __name__ == "__main__":
    s = Spider(host='127.0.0.1', port=3306,
               user='root', password='.....',
               database='xiaoshuo', charset='utf8')

    s.run()

标签:20.3,20,get,Python,res,self,cursor,book,def
From: https://www.cnblogs.com/dream-ze/p/17281187.html

相关文章

  • 2023年4月2日(软件工程日报)
    今日学习内容:python深度学习了解python相关外部库,感知机部分知识首先numpy库    之后是matplotlib库       ......
  • 塔猫 | Python 日期时间格式化输出,带年、月、日、时、分、秒
    #依赖:importtime|用于:批量文件名后缀(4位浮点秒数,应该没人猜到,当做随机数)defftime(f=''):iff=='-':returntime.strftime('%Y-%m-%d%H:%M:%S',time.localtime())iff=='':timeStamp=time.time()ends......
  • Day 21 21.2 数据库之Python操作redis
    Python操作redis(1)连接redis#方式1importredisr=redis.Redis(host='127.0.0.1',port=6379)r.set('foo','Bar')print(r.get('foo'))#方式2importredispool=redis.ConnectionPool(host='127.0.0.1',port=63......
  • 在Android应用中通过Chaquopy使用Python
    在Android应用中通过Chaquopy使用Python[译]通过Python脚本和包为Android应用带来更多的功能翻译自https://proandroiddev.com/chaquopy-using-python-in-android-apps-dd5177c9ab6b欢迎通过我的Blog访问此文章.Python在开发者社区中时最受欢迎的语言之一,因为其简单,健......
  • Day 21 21.4 数据库之Python操作MongoDB
    PyMongo在这里我们来看一下Python3下MongoDB的存储操作,在本节开始之前请确保你已经安装好了MongoDB并启动了其服务,另外安装好了Python的PyMongo库。安装:pipinstallpymongo添加文档importpymongoclient=pymongo.MongoClient(host='localhost',port=27017)"""......
  • 【Pandas数据处理100例目录】Python数据分析玩转Excel表格数据
    前言大家好,我是阿光。本专栏整理了《Pandas数据分析处理》,内包含了各种常见的数据处理,以及Pandas内置函数的使用方法,帮助我们快速便捷的处理表格数据。正在更新中~✨......
  • 2024届计算机秋招100天备战:力扣每日打卡挑战全记录 & 面试题总结
    最近两个月力扣困难题不再落下,打卡全满勤,激发了持续刷题的斗志。这里将持续记录打卡过程中的难题和面试八股。2023/4/21039.多边形三角剖分的最低得分题目大意:多边形每个节点有一个数值,将多边形三角剖分,得分为所有三角形节点乘积之和。求三角剖分后的最低得分。做题评价:虽......
  • 云锵投资 2023 年 3 月简报
    2023年3月云锵投资团队月报:摘要本月量化基金策略业绩:中;本月量化股票策略业绩:差;(优良中差,表明全国排名四位分)云锵投资概述云锵量化投资包含量化投基、量化投股。量化投基使用自动化程序进行量化选基。其中包含了多个策略。本集合投资目标是通过选择优质基金,来获取更高的......
  • Python | 解决方案 | 多个文件共用logger,重复打印问题
    项目中封装了logging库为log.py,实现既把日志输出到控制台,又写入日志文件文件。环境:python3.7.3项目中,多个文件共用logger,出现重复打印问题,解决流程记录如下:文件和调用方式如下:log.pyv1#encoding=utf-8####@Description:日志封装文件#@Author:fatih#@Dat......
  • 联合省选 2023 游记
    \(\texttt{2023.3.31}\)(试机日)咕咕咕。\(\texttt{2023.4.1}\)(联合省选2023Day1)愚人节快乐!咕咕咕。期望得分\(100+[75,100]+48=[223,248]\)。\(\texttt{2023.4.2}\)(联合省选2023Day2)咕咕咕。实在是太丢人了!期望得分\(35+[64,72]+[0,10]=[99,117]\)。但是无所谓,我会......