99999久久久久久亚洲,欧美人与禽猛交狂配,高清日韩av在线影院,一个人在线高清免费观看,啦啦啦在线视频免费观看www

熱線電話:13121318867

登錄
首頁精彩閱讀使用Python連接MySQL數(shù)據(jù)庫
使用Python連接MySQL數(shù)據(jù)庫
2018-01-10
收藏

使用Python連接MySQL數(shù)據(jù)庫

本篇文章使用python中的pymysql庫連接MySQL數(shù)據(jù)庫,并完成建表,數(shù)據(jù)寫入和查詢的過程。為了保證內(nèi)容的完整性,我們將內(nèi)容分為兩個 階段,第一階段簡單介紹數(shù)據(jù)的爬取過程。看過之前爬蟲文章的同學請直接忽略。第二階段介紹將爬去的數(shù)據(jù)寫入MySQL數(shù)據(jù)庫的過程。

1,使用python抓取并提取數(shù)據(jù)

第一階段介紹數(shù)據(jù)爬取過程,首先導入所需的庫文件,主要包括requests,re和pandas三個庫。具體作用在注釋中進行了說明,這里不再贅述。
    #導入requests庫(請求和頁面抓取)
    import requests
    #導入正則庫(從頁面代碼中提取信息)
    import re
    #導入科學計算庫(拼表及各種分析匯總)
    import pandas as pd
設置爬取請求中的頭文件信息。
    #設置請求中頭文件的信息
    headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64  
    Safari/537.11',
    'Accept':'text/html;q=0.9,*/*;q=0.8',
    'Accept-Charset':'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
    'Connection':'close',
    'Referer':'https://www.baidu.com/'
    }

開始抓取數(shù)據(jù),并查看抓取到的網(wǎng)頁內(nèi)容。這里我們所需要的數(shù)據(jù)還在頁面源碼中,需要使用正則表達式進行提取。
    #抓取并保存頁面信息
    r=requests.get('http://www.p2peye.com/shuju/ptsj/',headers=headers)
    html=r.content
    #對抓取的頁面進行編碼
    html=str(html, encoding = "GBK")
    #查看抓取的頁面源碼
    html

使正則表達式從抓取到的網(wǎng)頁源碼中提取所需數(shù)據(jù)。這里我們一共提取9個字段。
    #使用正則提取title字段信息
    title=re.findall(r'"return false".*?title="(.*?)"',html)
    #使用正則提取total字段信息
    total=re.findall(r'"total">(.*?)萬<',html)
    #使用正則提取rate字段信息
    rate=re.findall(r'"rate">(.*?)<',html)
    #使用正則提取pnum字段信息
    pnum=re.findall(r'"pnum">(.*?)人<',html)
    #使用正則提取cycle字段信息
    cycle=re.findall(r'"cycle">(.*?)月<',html)
    #使用正則提取plnum字段信息
    p1num=re.findall(r'"p1num">(.*?)人<',html)
    #使用正則提取fuload字段信息
    fuload=re.findall(r'"fuload">(.*?)分鐘<',html)
    #使用正則提取alltotal字段信息
    alltotal=re.findall(r'"alltotal">(.*?)萬<',html)
    #使用正則提取captial字段信息
    capital=re.findall(r'"capital">(.*?)萬<',html)
查看其中一個字段的信息,這里我們查看平臺名稱title的提取結(jié)果。
    #查看title字段信息
    title

到這里第一階段的數(shù)據(jù)爬取工作完成了,現(xiàn)在我們有9個字段的數(shù)據(jù),在下一階段中我們將連接MySQL數(shù)據(jù)庫,并將這9個字段的數(shù)據(jù)寫到數(shù)據(jù)庫里。
2,連接MySQL數(shù)據(jù)庫寫入并讀取數(shù)據(jù)
在第二階段,我們使用python的pymysql庫連接MySQL數(shù)據(jù)庫。如果你是第一次使用這個庫需要先通過pip install pymysql進行安裝,然后導入pymysql庫文件。

    #導入pymysql
    import pymysql
首先連接MySQL數(shù)據(jù)庫,這里需要輸入數(shù)據(jù)庫的ip地址,用戶名,密碼,數(shù)據(jù)庫名稱,端口號等信息。我在這里只簡單些了ip地址,用戶名和數(shù)據(jù)庫名稱。每個參數(shù)的內(nèi)容請按你數(shù)據(jù)庫的實際信息進行填寫。
    #打開數(shù)據(jù)庫連接
    db = pymysql.connect("192.168.0.1","root","","shuju_test" )

使用 cursor()創(chuàng)建一個游標對象

    # 使用 cursor() 方法創(chuàng)建一個游標對象 cursor
    cursor = db.cursor()
在數(shù)據(jù)庫中創(chuàng)建一個包含9個字段的數(shù)據(jù)表,用于寫入數(shù)據(jù)。這里具體分為兩步,第一步寫出創(chuàng)建數(shù)據(jù)表的SQL語句。第二步使用execute()執(zhí)行SQL語句

    #創(chuàng)建一個表
    sql1 = "CREATE TABLE wdty7( title varchar(255), total varchar(255), rate varchar(255), people_num varchar(255), cycle  
    varchar(255), people_lend_num varchar(255), full_load varchar(255), all_total varchar(255), capital varchar(255)) "
      
    # 使用 execute() 方法執(zhí)行 SQL 語句
    cursor.execute(sql1)

創(chuàng)建完數(shù)據(jù)表后,開始寫入數(shù)據(jù),這里我們使用for循環(huán)向數(shù)據(jù)表中逐條寫入9個字段的數(shù)據(jù)。
    #向表中創(chuàng)建新的記錄
    for i in range(len(title)):
    sql="INSERT INTO `wdty6`(`title`, `total`, `rate`, `people_num`, `cycle`, `people_lend_num`, `full_load`, `all_total`,  
    `capital`)VALUES ( %s, %s, %s, %s, %s, %s, %s, %s, %s);"
    values=(title[i].encode("utf-7").decode("latin1"),total[i],rate[i],pnum[i],cycle[i],p1num[i],fuload[i],alltotal  
    [i],capital[i])
    cursor.execute(sql,values)
    db.commit()
創(chuàng)建一個查詢語句并使用execute()方法執(zhí)行查詢。
    #設置查詢語句
    sql1="SELECT * FROM wdty6 where cycle>0.6;"
      
    # 使用 execute() 方法執(zhí)行 SQL 查詢  
    cursor.execute(sql1)

使用fetchall()獲取剛才寫入的所有9個字段的數(shù)據(jù),并保存在data中。

    #使用fetchall()方法獲取所有數(shù)據(jù)
    data = cursor.fetchall()
將data中的數(shù)據(jù)轉(zhuǎn)為pandasDataFrame格式。
    #將獲取數(shù)據(jù)
    import pandas as pd
    columns=["title", "total", "rate", "people_num", "cycle", "people_lend_num", "full_load", "all_total", "capital"]
    df = pd.DataFrame(list(data),columns=columns)
查看從數(shù)據(jù)庫中提取的數(shù)據(jù),這里有個問題,平臺名稱title字段中的中文在寫入數(shù)據(jù)庫后變成了亂碼,應該是編碼轉(zhuǎn)換的問題。目前還沒有找到解決辦法。如有知道解決辦法的朋友請賜教。
    #查看數(shù)據(jù)表  
    df.head()
使用Python連接MySQL數(shù)據(jù)庫
最后,完成所有操作后關(guān)閉數(shù)據(jù)庫的連接。
    # 關(guān)閉數(shù)據(jù)庫連接
    db.close()


數(shù)據(jù)分析咨詢請掃描二維碼

若不方便掃碼,搜微信號:CDAshujufenxi

數(shù)據(jù)分析師資訊
更多

OK
客服在線
立即咨詢
客服在線
立即咨詢
') } function initGt() { var handler = function (captchaObj) { captchaObj.appendTo('#captcha'); captchaObj.onReady(function () { $("#wait").hide(); }).onSuccess(function(){ $('.getcheckcode').removeClass('dis'); $('.getcheckcode').trigger('click'); }); window.captchaObj = captchaObj; }; $('#captcha').show(); $.ajax({ url: "/login/gtstart?t=" + (new Date()).getTime(), // 加隨機數(shù)防止緩存 type: "get", dataType: "json", success: function (data) { $('#text').hide(); $('#wait').show(); // 調(diào)用 initGeetest 進行初始化 // 參數(shù)1:配置參數(shù) // 參數(shù)2:回調(diào),回調(diào)的第一個參數(shù)驗證碼對象,之后可以使用它調(diào)用相應的接口 initGeetest({ // 以下 4 個配置參數(shù)為必須,不能缺少 gt: data.gt, challenge: data.challenge, offline: !data.success, // 表示用戶后臺檢測極驗服務器是否宕機 new_captcha: data.new_captcha, // 用于宕機時表示是新驗證碼的宕機 product: "float", // 產(chǎn)品形式,包括:float,popup width: "280px", https: true // 更多配置參數(shù)說明請參見:http://docs.geetest.com/install/client/web-front/ }, handler); } }); } function codeCutdown() { if(_wait == 0){ //倒計時完成 $(".getcheckcode").removeClass('dis').html("重新獲取"); }else{ $(".getcheckcode").addClass('dis').html("重新獲取("+_wait+"s)"); _wait--; setTimeout(function () { codeCutdown(); },1000); } } function inputValidate(ele,telInput) { var oInput = ele; var inputVal = oInput.val(); var oType = ele.attr('data-type'); var oEtag = $('#etag').val(); var oErr = oInput.closest('.form_box').next('.err_txt'); var empTxt = '請輸入'+oInput.attr('placeholder')+'!'; var errTxt = '請輸入正確的'+oInput.attr('placeholder')+'!'; var pattern; if(inputVal==""){ if(!telInput){ errFun(oErr,empTxt); } return false; }else { switch (oType){ case 'login_mobile': pattern = /^1[3456789]\d{9}$/; if(inputVal.length==11) { $.ajax({ url: '/login/checkmobile', type: "post", dataType: "json", data: { mobile: inputVal, etag: oEtag, page_ur: window.location.href, page_referer: document.referrer }, success: function (data) { } }); } break; case 'login_yzm': pattern = /^\d{6}$/; break; } if(oType=='login_mobile'){ } if(!!validateFun(pattern,inputVal)){ errFun(oErr,'') if(telInput){ $('.getcheckcode').removeClass('dis'); } }else { if(!telInput) { errFun(oErr, errTxt); }else { $('.getcheckcode').addClass('dis'); } return false; } } return true; } function errFun(obj,msg) { obj.html(msg); if(msg==''){ $('.login_submit').removeClass('dis'); }else { $('.login_submit').addClass('dis'); } } function validateFun(pat,val) { return pat.test(val); }