pymysql操作MySQL数据库表-----爬虫豆瓣top250电影并存入数据库

import requests
import pymysql
from bs4 import BeautifulSoup


def parse_result(html,db,cursor):

    soup = BeautifulSoup(html,features='html.parser')
    """
    html 表示被解析的html格式的内容
    html.parser表示解析用的解析器
    """
    list = soup.find(class_='grid_view').find_all('li')

    for item in list:

        item_name = item.find(class_='title').string
        item_img = item.find('a').find('img').get('src')
        # item_index = item.find(class_='').string
        item_index = item.find('em').string
        item_score = item.find(class_='rating_num').string
        item_author = item.find('p').text
        if(item.find(class_='inq')!=None):
            item_intr = item.find(class_='inq').string

        print('爬取电影:' + item_index + ' | ' + item_name  +' | ' + item_score  +' | ' + item_intr )

        sql = "insert into movies (id,name,score,intr) values (%s,'%s',%s,'%s')" %(item_index,item_name,item_score,pymysql.escape_string(item_intr))

        # db.ping(reconnect=True)
        # cursor = db.cursor()
        cursor.execute(sql)
        db.commit()

def request_douban(url):
    header = {
        'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36'
    }
    response = requests.get(url,headers=header)
    if response.status_code == 200:
        html = response.text
        return html
    else:
        print("获取网页失败")



if __name__ == '__main__':
    '''
    创建mysql连接
    '''
    #打开数据库连接,参数1:主机或IP;参数2:数据库账户名;参数3:数据库密码;参数4:数据库库名
    db = pymysql.connect('127.0.0.1','root','Change0224','myPython')
    #使用cursor()方法创建游标
    cursor = db.cursor()
    sql = "drop table if exists movies"
    #使用exectute()方法执行sql查询
    cursor.execute(sql)
    sql = '''
            create table movies (
            id int(8) not null auto_increment,
            name  varchar(50) not null,
            score float not null,
            intr varchar(50) not null,
            PRIMARY key (id)) engine = InnoDB
        '''
    cursor.execute(sql)

    for page in range(0,10):
        url = 'https://movie.douban.com/top250?start={}&filter='.format(page*25)
        html = request_douban(url)
        parse_result(html,db,cursor)

    cursor.close()
    db.close()

tips:

1、pymysql操作数据库


import pymysql

#第一步:创建mysql连接
db = pymysql.connect('127.0.0.1','root','Change0224','myPython')
#第二步:使用cursor()方法创建一个游标对象
cursor = db.cursor()
sql = "drop table if exists movies"
#第三步:使用execute()执行语句
cursor.execute(sql)
sql = '''
        create table movies (
        id int(8) not null auto_increment,
        name  varchar(50) not null,
        score float not null,
        intr varchar(50) not null,
        PRIMARY key (id)) engine = InnoDB
    '''
cursor.execute(sql)


data = [(1,'肖申克的救赎',9.7,'希望让人自由。'),
        (2,'霸王别姬',9.6,'风华绝代。'),
        (3,'喜剧之王',8.7,'我是一个演员。'),
        (4,'告白',8.7,'没有一人完全善,也没有一人完全恶。'),
        (5,'超能陆战队',8.7,'Balalala~~~'),
        (6,'神偷奶爸',8.6,'Mr. I Don\'t Care其实也有Care的时候。')]


sql = 'insert into movies (id,name,score,intr) values (%s,%s,%s,%s)'

try:
    # 批量插入多条语句
    cursor.executemany(sql,data)
    #第四步:提交数据
    db.commit()
except:
    #发生错误时回滚
    db.rollback()
#第五步:关闭游标,关闭连接
cursor.close()
db.close()

多条插入使用 cursor.executemany()方法

遇到报错:not all arguments converted during string formatting python

报错原因:说明前后%和后面的参数数量不对应,有n个字段,就要有n个%s

2、在操作插入数据的时候,由于数据中存在单引号或者双引号导致报错:

例data="Mr. I Don't Care其实也有Care的时候。"

执行单条插入语句为:

#插入字段为字符串,%s注意加上引号
sql = "insert into tb (my_str) values('%s')" % (data)
cursor.execute(sql)

 经过百度查询,提到在MySQLdb模块中自带针对mysql的转义函数escape_string(),直接调用即可。

经过实际操作发现该方法不可行:MySQLdb 只支持Python 2.* ,暂时还不支持3.*

实现方法如下:

import pymysql

sql = "insert into tb (my_str) values('%s')" % (pymysql.escape_string(data))
cursor.execute(sql)

3、cur.execute(sql,args)和cur.execute(sql)的区别

方式一:

userid = “123”
sql = “select id,name from user where id = ‘%s’” % userid
cur.execute(sql)

方式二:
“”"
sql语句模板中的参数填充符是 %s 而不是 ‘%s’ ,且多个参数需要用元祖存放,单个参
数可直接传递
“”"
userid = “123”
sql = "“select id,name from user where id = %s and name =%s”
cur.execute(sql, (‘123’, ‘云天明’))

区别:
方式一会存在sql注入的风险,方式二中用python内置的方法可以对sql语句中传入的参数进行校验,在一定程度上屏蔽掉sql注入,增加了sql的安全性,在不便直接使用sqlArchemy框架(底层实现也是调用的方式二)的情况下,建议选择方式二。

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值