python爬虫练习,爬取数据写入MySQL数据库

本次爬取内容就选取章节名和章节链接作为举例
url:http://www.xbiquge.la/0/215/
python爬虫练习,爬取数据写入MySQL数据库_第1张图片
数据库操作的基本方法:
1):连接数据库
2):获取数据库游标
3):执行sql语句
4):断开数据库连接

# 连接数据库,参数包括IP、用户名、密码、对应的库名
        connect = pymysql.connect('localhost', 'root', 'gui2019', 'python')
        # 数据库游标
        course = connect.cursor()
        # 插入语句
        sql = "INSERT INTO kongfu values(default, '%s', '%s')  " % (title_name, newUrl)
        try:
            print("正在写入数据 ---->>>>: ", title_name)
            course.execute(sql)
            connect.commit()
        except Exception as e:
            print('数据写入失败!', e)
            connect.rollback()
            connect.close()

运行效果如图所示: python爬虫练习,爬取数据写入MySQL数据库_第2张图片

完整代码如下:
要运行下面的代码需要现在mysql创建python数据库,kongfu表。 表结构如下图: python爬虫练习,爬取数据写入MySQL数据库_第3张图片

#  引入第三方库
import requests
import re
import pymysql

def get_data():
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36'
    }
    # 小说目录URL
    url = 'http://www.xbiquge.la/0/215/'
    html = requests.get(url, headers=headers).content.decode('utf-8')
    pat = r"
(.*?)
" list = re.findall(pat, html) return list def db_connect(list): for i in list: title_url = i[0] title_name = i[1] newUrl = 'http://www.xbiquge.la' + title_url # 连接数据库,参数包括IP、用户名、密码、对应的库名 connect = pymysql.connect('localhost', 'root', 'gui2019', 'python') # 数据库游标 course = connect.cursor() # 插入语句 sql = "INSERT INTO kongfu values(default, '%s', '%s') " % (title_name, newUrl) try: print("正在写入数据 ---->>>>: ", title_name) course.execute(sql) connect.commit() except Exception as e: print('数据写入失败!', e) connect.rollback() connect.close() def main(): list = get_data() db_connect(list) if __name__ == '__main__': main()

你可能感兴趣的:(爬虫,python,mysql,爬虫)