数据存储之使用mysql数据库存储数据

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_34363070/article/details/84503997

推荐安装mysql5.7环境:

  1. 官网下载:https://dev.mysql.com/downloads/installer/5.7.html
  2. 如果提示没有.NET Framework框架。那么就在提示框中找到下载链接,下载一个就可以了。
  3. 如果提示没有Microsoft Virtual C++ x64(x86),那么百度或者谷歌这个软件安装即可。

Navicat Premium 版本:

navicat是一个操作mysql数据库非常方便的软件。使用他操作数据库,就跟使用excel操作数据是一样的。

1.官网下载:http://www.navicat.com.cn/download/navicat-premium

推荐使用 (官网最新版的没有破解成功,推荐这个版本)Navicat Premium 12.0.27简体中文64位,密码: s9f8

破解成功图

2.破解参考
https://blog.csdn.net/pippa134679/article/details/81354131
https://www.jianshu.com/p/5f693b4c9468

安装驱动程序:

Python要想操作MySQL。必须要有一个中间件,或者叫做驱动程序。驱动程序有很多。比如有mysqldbmysqlclientpymysql等。在这里,我们选择用pymysql。安装方式也是非常简单,通过命令pip install pymysql即可安装。

数据库连接:

数据库连接之前。首先先确认以下工作完成,这里我们以一个pymysql_test数据库.以下将介绍连接mysql的示例代码:

    import pymysql

    db = pymysql.connect(
        host="127.0.0.1",
        user='root',
        password='root',
        database='pymysql_test',
        port=3306
    )
    cursor = db.cursor()
    cursor.execute("select 1")
    data = cursor.fetchone()
    print(data)
    db.close()

插入数据:

import pymysql

db = pymysql.connect(
    host="127.0.0.1",
    user='root',
    password='root',
    database='pymysql_test',
    port=3306
)
cursor = db.cursor()
sql = """
insert into user(
    id,username,gender,age,password
  )
  values(null,'abc',1,18,'111111');
"""
cursor.execute(sql)
db.commit()
db.close()

如果在数据还不能保证的情况下,可以使用以下方式来插入数据:

sql = """
insert into user(
    id,username,gender,age,password
  )
  values(null,%s,%s,%s,%s);
"""

cursor.execute(sql,('spider',1,20,'222222'))

查找数据:

使用pymysql查询数据。可以使用fetch*方法。

  1. fetchone():这个方法每次之获取一条数据。
  2. fetchall():这个方法接收全部的返回结果。
  3. fetchmany(size):可以获取指定条数的数据。
    示例代码如下:
cursor = db.cursor()

sql = """
select * from user
"""

cursor.execute(sql)
while True:
    result = cursor.fetchone()
    if not result:
        break
    print(result)
db.close()

或者是直接使用fetchall,一次性可以把所有满足条件的数据都取出来:

cursor = db.cursor()

sql = """
select * from user
"""

cursor.execute(sql)
results = cursor.fetchall()
for result in results:
    print(result)
db.close()

或者是使用fetchmany,指定获取多少条数据:

cursor = db.cursor()

sql = """
select * from user
"""

cursor.execute(sql)
results = cursor.fetchmany(1)
for result in results:
    print(result)
db.close()

删除数据:

cursor = db.cursor()

sql = """
delete from user where id=1
"""

cursor.execute(sql)
db.commit()
db.close()

更新数据:

conn = pymysql.connect(host='localhost',user='root',password='root',database='pymysql_demo',port=3306)
cursor = conn.cursor()

sql = """
update user set username='aaa' where id=1
"""
cursor.execute(sql)
conn.commit()

conn.close()

实战抓取安居客广西南宁全区的租房信息(正则表达式,MySQL数据库保存)

import requests
import re
import pymysql

# 实战抓取安居客广西南宁全区的租房信息(正则表达式,数据库保存)
headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'
}


def insert_house_detail(url):
    print(url)
    # 连接数据库和添加数据
    conn = pymysql.connect(host='localhost', user='root', password='password', database='zufang', port=3306)
    cursor = conn.cursor()

    # 添加数据
    sql = """
    insert into house(id,title,img,price,payType,leaseType,houseType,address,detail) values(null,%s,%s,%s,%s,%s,%s,%s,%s)
    """

    # 获取数据并添加到数据库
    response = requests.get(url, headers=headers)
    text = response.text
    title = re.findall(r'<h3\sclass="house-title">(.*?)</h3>', text, re.DOTALL)[0]
    img = re.findall(r'<div\sclass="img_wrap">.*?<img\sdata-src="(.*?)".*?>', text, re.DOTALL)[0]
    price = re.findall(r'<span\sclass="price">.*?<em>(.*?)</em>', text, re.DOTALL)[0]
    payType = re.findall(r'<span\sclass="type">(.*?)</span>', text, re.DOTALL)[0]
    leaseType = re.findall(r'<span\sclass="info">(.*?)</span>', text, re.DOTALL)[1]
    houseType = re.findall(r'<span\sclass="info">(.*?)</span>', text, re.DOTALL)[0]
    # houseType = re.findall(r'<ul.*?class="f14">.*?<span\sclass="c_888 mr_15">.*?<span>(.*?)</span>.*?</li>', text, re.DOTALL)[0].replace('                                ', '').replace('&nbsp;', '').strip()

    address = re.findall(r'<li\sclass="house-info-item l-width">.*?<a.*?>(.*?)</a>', text, re.DOTALL)
    detail_tag = re.findall(r'<div\sclass="auto-general">(.*?)</div>', text, re.DOTALL)[0]
    # 去掉抓取到标签和空格
    detail = re.sub('<.+?>', "", detail_tag).replace('                                ', '').strip()


    cursor.execute(sql, (title, img, price, payType, leaseType, houseType, address, detail))
    conn.commit()
    conn.close()


def parse_page(url):

    response = requests.get(url, headers=headers)
    text = response.text
    # 先获取url
    urls = re.findall(r'<div\sclass="zu-info">.*?<a.*?href="(.*?)".*?>.*?</a>', text, re.DOTALL)[1:-2]

    for index,url_tag in enumerate(urls):
        insert_house_detail(url_tag)


def main():
    for x in range(1,21):
        url = 'https://nn.zu.anjuke.com/fangyuan/p%s/' % x
        parse_page(url)


if __name__ == '__main__':
    main()

更多Python实战源码请关注 朝南而行 公众号

朝南而行

上一篇:数据解析之正则表达式和re模块
下一篇:数据存储之使用Mongodb数据库存储数据

猜你喜欢

转载自blog.csdn.net/qq_34363070/article/details/84503997