數(shù)據(jù)存儲之使用mysql數(shù)據(jù)庫存儲數(shù)據(jù)

推薦安裝mysql5.7環(huán)境:

  1. 官網(wǎng)下載:https://dev.mysql.com/downloads/installer/5.7.html
  2. 如果提示沒有.NET Framework框架。那么就在提示框中找到下載鏈接,下載一個就可以了。
  3. 如果提示沒有Microsoft Virtual C++ x64(x86),那么百度或者谷歌這個軟件安裝即可。

Navicat Premium 版本:

navicat是一個操作mysql數(shù)據(jù)庫非常方便的軟件。使用他操作數(shù)據(jù)庫,就跟使用excel操作數(shù)據(jù)是一樣的。

1.官網(wǎng)下載:http://www.navicat.com.cn/download/navicat-premium

推薦使用 (官網(wǎng)最新版的沒有破解成功,推薦這個版本)Navicat Premium 12.0.27簡體中文64位,密碼: s9f8

破解成功圖

2.破解參考
https://blog.csdn.net/pippa134679/article/details/81354131
http://www.itdecent.cn/p/5f693b4c9468

安裝驅(qū)動程序:

Python要想操作MySQL。必須要有一個中間件,或者叫做驅(qū)動程序。驅(qū)動程序有很多。比如有mysqldb、mysqlclient、pymysql等。在這里,我們選擇用pymysql。安裝方式也是非常簡單,通過命令pip install pymysql即可安裝。

數(shù)據(jù)庫連接:

數(shù)據(jù)庫連接之前。首先先確認(rèn)以下工作完成,這里我們以一個pymysql_test數(shù)據(jù)庫.以下將介紹連接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()

插入數(shù)據(jù):

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()

如果在數(shù)據(jù)還不能保證的情況下,可以使用以下方式來插入數(shù)據(jù):

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

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

查找數(shù)據(jù):

使用pymysql查詢數(shù)據(jù)。可以使用fetch*方法。

  1. fetchone():這個方法每次之獲取一條數(shù)據(jù)。
  2. fetchall():這個方法接收全部的返回結(jié)果。
  3. fetchmany(size):可以獲取指定條數(shù)的數(shù)據(jù)。
    示例代碼如下:
cursor = db.cursor()

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

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

或者是直接使用fetchall,一次性可以把所有滿足條件的數(shù)據(jù)都取出來:

cursor = db.cursor()

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

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

或者是使用fetchmany,指定獲取多少條數(shù)據(jù):

cursor = db.cursor()

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

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

刪除數(shù)據(jù):

cursor = db.cursor()

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

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

更新數(shù)據(jù):

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()

實(shí)戰(zhàn)抓取安居客廣西南寧全區(qū)的租房信息(正則表達(dá)式,MySQL數(shù)據(jù)庫保存)

import requests
import re
import pymysql

# 實(shí)戰(zhàn)抓取安居客廣西南寧全區(qū)的租房信息(正則表達(dá)式,數(shù)據(jù)庫保存)
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)
    # 連接數(shù)據(jù)庫和添加數(shù)據(jù)
    conn = pymysql.connect(host='localhost', user='root', password='password', database='zufang', port=3306)
    cursor = conn.cursor()

    # 添加數(shù)據(jù)
    sql = """
    insert into house(id,title,img,price,payType,leaseType,houseType,address,detail) values(null,%s,%s,%s,%s,%s,%s,%s,%s)
    """

    # 獲取數(shù)據(jù)并添加到數(shù)據(jù)庫
    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]
    # 去掉抓取到標(biāo)簽和空格
    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()

上一篇:數(shù)據(jù)存儲之json文件處理和csv文件處理
下一篇:數(shù)據(jù)存儲之使用Mongodb數(shù)據(jù)庫存儲數(shù)據(jù)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容