python3 Mysql保存爬取的数据(正则提取关键信息)

Python 爬虫目录
        
        1、Python3 爬取前程无忧招聘网 lxml+xpath
        2、Python3 Mysql保存爬取的数据 正则
        3、Python3 用requests 库 和 bs4 库 最新爬豆瓣电影Top250
        4、Python Scrapy 爬取 前程无忧招聘网
        5、持续更新…
        
        
        
本文爬取网站地址:https://www.xzw.com/fortune/
在这里插入图片描述
前提是要有Mysql (过几天会发布一篇MAC 下Mysql8.0版本的博客)

开始分析文章

在这里插入图片描述
图中信息就是我们需要爬取的
正则表达式:re.compile(r'^.*?<strong>(.*?)</strong><small>(.*?)</small>.*?width:(\d*)%.*?p>(.*)\[<a.*$',re.S)
总之,爬取这网站,简单,主要是介绍mysql连接和保存数据

Mysql的连接

 # 创建连接
    db = pymysql.Connect(
        host='localhost',  # mysql服务器地址
        port=3306,  # mysql服务器端口号
        user='root',  # 用户名
        passwd='123123',  # 密码
        db='save_data',  # 数据库名
        charset='utf8'  # 连接编码
    )

创建完连接后,还需要创建操作游标。

# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
 
# 使用 execute() 方法执行 SQL,如果表存在则删除
cursor.execute("DROP TABLE IF EXISTS TableName")
 
# 使用预处理语句创建表
sql = """CREATE TABLE TableName (
         FIRST_NAME  CHAR(20) NOT NULL,
         LAST_NAME  CHAR(20),
         AGE INT,  
         SEX CHAR(1),
         INCOME FLOAT )"""
 
cursor.execute(sql)
 
# 关闭数据库连接
db.close()

如果插入向Mysql插入数据,最好使用下面的语法

sql = """INSERT INTO TableName(field)
         VALUES (value)"""
try:
   # 执行sql语句
   cursor.execute(sql)
   # 提交到数据库执行
   db.commit()
except:
   # 如果发生错误则回滚
   db.rollback()

完整代码如下

import requests
from bs4 import BeautifulSoup
import re
import pymysql



# 网页地址
baseurl = 'https://www.xzw.com/fortune/'

# 提取信息的正则表达式
fetch_re = re.compile(r'^.*?<strong>(.*?)</strong><small>(.*?)</small>.*?width:(\d*)%.*?p>(.*)\[<a.*$',re.S)


def fetch_msg():
    data = []
    resp = requests.get(baseurl).text
    # print(resp)   for test
    bs = BeautifulSoup(resp, 'html.parser')
    dls = bs.select('div.alb div dl')
    # print(dls)   for test
    for x in dls:
        star_data = {}
        # print(x)  for test
        result = fetch_re.match(str(x))
        # 星座
        star_data['xingzuo'] = result.group(1)
        # 出生时间
        star_data['birthday_time'] = result.group(2)
        # 时运指数
        star_data['index'] = str(int(result.group(3))/20)
        # 时运描述
        star_data['describe'] = result.group(4)
        data.append(star_data)
    # print(data)   for test

    # 创建连接
    db = pymysql.Connect(
        host='localhost',  # mysql服务器地址
        port=3306,  # mysql服务器端口号
        user='root',  # 用户名
        passwd='123123',  # 密码
        db='save_data',  # 数据库名
        charset='utf8'  # 连接编码
    )
    # 创建游标
    cursor = db.cursor()
    # drop = "drop table if exists star_info"
    sql = """CREATE TABLE star_info(
            ID INT PRIMARY KEY AUTO_INCREMENT COMMENT 'ID' ,
            constellation varchar(12)  COMMENT '星座' ,
            Birthday_time varchar (20) COMMENT '出生时间',
            Forture_score FLOAT DEFAULT '0.0' COMMENT '运势指数',
            today_forture varchar (100)  COMMENT '运势描述')ENGINE=InnoDB DEFAULT CHARSET=UTF8MB4 COMMENT '星座信息表';
            """
    cursor.execute(sql)
    for i in data:
        info = "INSERT INTO star_info(constellation,Birthday_time,Forture_score,today_forture) values (%s,%s,%s,%s)"%(repr(i['xingzuo']), repr(i['birthday_time']), i['index'], repr(i['describe']))
        cursor.execute(info)   # 这里是一条一条的插入数据库
    
    # 关闭游标
    cursor.close()    
    # 提交事务
    db.commit()
    #关闭数据库连接
    db.close()



if __name__ =='__main__':
    fetch_msg()

这里需安装pymysql库,如果在Pycharm 安装失败,你可以用Pycharm里的终端 输入:

 pip3 install -i https://pypi.tuna.tsinghua.edu.cn/simple pymysql

猜你喜欢

转载自blog.csdn.net/weixin_45215649/article/details/107192544
今日推荐