使用Python連接MySQL數(shù)據(jù)庫
本篇文章使用python中的pymysql庫連接MySQL數(shù)據(jù)庫,并完成建表,數(shù)據(jù)寫入和查詢的過程。為了保證內(nèi)容的完整性,我們將內(nèi)容分為兩個(gè) 階段,***階段簡單介紹數(shù)據(jù)的爬取過程。看過之前爬蟲文章的同學(xué)請直接忽略。第二階段介紹將爬去的數(shù)據(jù)寫入MySQL數(shù)據(jù)庫的過程。
1,使用python抓取并提取數(shù)據(jù)
***階段介紹數(shù)據(jù)爬取過程,首先導(dǎo)入所需的庫文件,主要包括requests,re和pandas三個(gè)庫。具體作用在注釋中進(jìn)行了說明,這里不再贅述。
- #導(dǎo)入requests庫(請求和頁面抓取)
- import requests
- #導(dǎo)入正則庫(從頁面代碼中提取信息)
- import re
- #導(dǎo)入科學(xué)計(jì)算庫(拼表及各種分析匯總)
- import pandas as pd
設(shè)置爬取請求中的頭文件信息。
- #設(shè)置請求中頭文件的信息
- 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ù)還在頁面源碼中,需要使用正則表達(dá)式進(jìn)行提取。
- #抓取并保存頁面信息
- r=requests.get('http://www.p2peye.com/shuju/ptsj/',headers=headers)
- html=r.content
- #對抓取的頁面進(jìn)行編碼
- html=str(html, encoding = "GBK")
- #查看抓取的頁面源碼
- html

使正則表達(dá)式從抓取到的網(wǎng)頁源碼中提取所需數(shù)據(jù)。這里我們一共提取9個(gè)字段。
- #使用正則提取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)
查看其中一個(gè)字段的信息,這里我們查看平臺名稱title的提取結(jié)果。
- #查看title字段信息
- title
到這里***階段的數(shù)據(jù)爬取工作完成了,現(xiàn)在我們有9個(gè)字段的數(shù)據(jù),在下一階段中我們將連接MySQL數(shù)據(jù)庫,并將這9個(gè)字段的數(shù)據(jù)寫到數(shù)據(jù)庫里。
2,連接MySQL數(shù)據(jù)庫寫入并讀取數(shù)據(jù)
在第二階段,我們使用python的pymysql庫連接MySQL數(shù)據(jù)庫。如果你是***次使用這個(gè)庫需要先通過pip install pymysql進(jìn)行安裝,然后導(dǎo)入pymysql庫文件。
- #導(dǎo)入pymysql庫
- import pymysql
首先連接MySQL數(shù)據(jù)庫,這里需要輸入數(shù)據(jù)庫的ip地址,用戶名,密碼,數(shù)據(jù)庫名稱,端口號等信息。我在這里只簡單些了ip地址,用戶名和數(shù)據(jù)庫名稱。每個(gè)參數(shù)的內(nèi)容請按你數(shù)據(jù)庫的實(shí)際信息進(jìn)行填寫。
- #打開數(shù)據(jù)庫連接
- db = pymysql.connect("192.168.0.1","root","","shuju_test" )
使用 cursor()創(chuàng)建一個(gè)游標(biāo)對象
- # 使用 cursor() 方法創(chuàng)建一個(gè)游標(biāo)對象 cursor
- cursor = db.cursor()
在數(shù)據(jù)庫中創(chuàng)建一個(gè)包含9個(gè)字段的數(shù)據(jù)表,用于寫入數(shù)據(jù)。這里具體分為兩步,***步寫出創(chuàng)建數(shù)據(jù)表的SQL語句。第二步使用execute()執(zhí)行SQL語句
- #創(chuàng)建一個(gè)表
- 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個(gè)字段的數(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)建一個(gè)查詢語句并使用execute()方法執(zhí)行查詢。
- #設(shè)置查詢語句
- sql1="SELECT * FROM wdty6 where cycle>0.6;"
- # 使用 execute() 方法執(zhí)行 SQL 查詢
- cursor.execute(sql1)
使用fetchall()獲取剛才寫入的所有9個(gè)字段的數(shù)據(jù),并保存在data中。
- #使用fetchall()方法獲取所有數(shù)據(jù)
- data = cursor.fetchall()
將data中的數(shù)據(jù)轉(zhuǎn)為pandas的DataFrame格式。
- #將獲取數(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ù),這里有個(gè)問題,平臺名稱title字段中的中文在寫入數(shù)據(jù)庫后變成了亂碼,應(yīng)該是編碼轉(zhuǎn)換的問題。目前還沒有找到解決辦法。如有知道解決辦法的朋友請賜教。
- #查看數(shù)據(jù)表
- df.head()
***,完成所有操作后關(guān)閉數(shù)據(jù)庫的連接。
- # 關(guān)閉數(shù)據(jù)庫連接
- db.close()