Python入門(mén)只需20分鐘,從安裝到數(shù)據(jù)抓取、存儲(chǔ)原來(lái)這么簡(jiǎn)單
基于大眾對(duì)Python的大肆吹捧和贊賞,作為一名Java從業(yè)人員,看了Python的書(shū)籍之后,決定做一名python的腦殘粉。
作為一名合格的腦殘粉(標(biāo)題黨ノ◕ω◕)ノ),為了發(fā)展我的下線,接下來(lái)我會(huì)詳細(xì)的介紹Python的安裝到開(kāi)發(fā)工具的簡(jiǎn)單介紹,并編寫(xiě)一個(gè)抓取天氣信息數(shù)據(jù)并儲(chǔ)存到數(shù)據(jù)庫(kù)的例子。(這篇文章適用于完全不了解Python的小白超超超快速入門(mén))
如果有時(shí)間的話,強(qiáng)烈建議跟著一起操作一遍,因?yàn)榻榻B的真的很詳細(xì)了。
源碼視頻書(shū)籍練習(xí)題等資料可以私信小編01獲取
1、Python 安裝
2、PyCharm(ide) 安裝
3、抓取天氣信息
4、數(shù)據(jù)寫(xiě)入excel
5、數(shù)據(jù)寫(xiě)入數(shù)據(jù)庫(kù)
1、Python安裝
下載 Python: 官網(wǎng)地址: https://www.python.org/ 選擇download 再選擇你電腦系統(tǒng),小編是Windows系統(tǒng)的 所以就選擇
2、Pycharm安裝
下載 PyCharm : 官網(wǎng)地址:http://www.jetbrains.com/pycharm/
免費(fèi)版本的可以會(huì)有部分功能缺失,所以不推薦,所以這里我們選擇下載企業(yè)版。
安裝好 PyCharm,***打開(kāi)可能需要你 輸入郵箱 或者 輸入激活碼
獲取免費(fèi)的激活碼:http://idea.lanyus.com/
3、抓取天氣信息
我們計(jì)劃抓取的數(shù)據(jù):杭州的天氣信息,杭州天氣 可以先看一下這個(gè)網(wǎng)站。
實(shí)現(xiàn)數(shù)據(jù)抓取的邏輯:使用python 請(qǐng)求 URL,會(huì)返回對(duì)應(yīng)的 HTML 信息,我們解析 html,獲得自己需要的數(shù)據(jù)。(很簡(jiǎn)單的邏輯)
***步:創(chuàng)建 Python 文件
寫(xiě)***段Python代碼
- if __name__ == '__main__':
- url = 'http://www.weather.com.cn/weather/101210101.shtml'
- print('my frist python file')
這段代碼類似于 Java 中的 Main 方法。可以直接鼠標(biāo)右鍵,選擇 Run。

第二步:請(qǐng)求RUL
python 的強(qiáng)大之處就在于它有大量的模塊(類似于Java 的 jar 包)可以直接拿來(lái)使用。
我們需要安裝一個(gè) request 模塊: File - Setting - Product - Product Interpreter
點(diǎn)擊如上圖的 + 號(hào),就可以安裝 Python 模塊了。搜索
我們順便再安裝一個(gè) beautifulSoup4 和 pymysql 模塊,beautifulSoup4 模塊是用來(lái)解析 html 的,可以對(duì)象化 HTML 字符串。pymysql 模塊是用來(lái)連接 mysql 數(shù)據(jù)庫(kù)使用的。
相關(guān)的模塊都安裝之后,就可以開(kāi)心的敲代碼了。
定義一個(gè) getContent 方法:
- # 導(dǎo)入相關(guān)聯(lián)的包
- import requests
- import time
- import random
- import socket
- import http.client
- import pymysql
- from bs4 import BeautifulSoup
- def getContent(url , data = None):
- header={
- 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
- 'Accept-Encoding': 'gzip, deflate, sdch',
- 'Accept-Language': 'zh-CN,zh;q=0.8',
- 'Connection': 'keep-alive',
- 'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.235'
- } # request 的請(qǐng)求頭
- timeout = random.choice(range(80, 180))
- while True:
- try:
- rep = requests.get(url,headers = header,timeout = timeout) #請(qǐng)求url地址,獲得返回 response 信息
- rep.encoding = 'utf-8'
- break
- except socket.timeout as e: # 以下都是異常處理
- print( '3:', e)
- time.sleep(random.choice(range(8,15)))
- except socket.error as e:
- print( '4:', e)
- time.sleep(random.choice(range(20, 60)))
- except http.client.BadStatusLine as e:
- print( '5:', e)
- time.sleep(random.choice(range(30, 80)))
- except http.client.IncompleteRead as e:
- print( '6:', e)
- time.sleep(random.choice(range(5, 15)))
- print('request success')
- return rep.text # 返回的 Html 全文
在 main 方法中調(diào)用:
- if __name__ == '__main__':
- url ='http://www.weather.com.cn/weather/101210101.shtml'
- html = getContent(url) # 調(diào)用獲取網(wǎng)頁(yè)信息
- print('my frist python file')
第三步:分析頁(yè)面數(shù)據(jù)
定義一個(gè) getData 方法:
- def getData(html_text):
- final = []
- bs = BeautifulSoup(html_text, "html.parser") # 創(chuàng)建BeautifulSoup對(duì)象
- body = bs.body #獲取body
- data = body.find('div',{'id': '7d'})
- ul = data.find('ul')
- li = ul.find_all('li')
- for day in li:
- temp = []
- date = day.find('h1').string
- temp.append(date) #添加日期
- inf = day.find_all('p')
- weather = inf[0].string #天氣
- temp.append(weather)
- temperature_highest = inf[1].find('span').string #***溫度
- temperature_low = inf[1].find('i').string # ***溫度
- temp.append(temperature_low)
- temp.append(temperature_highest)
- final.append(temp)
- print('getDate success')
- return final
上面的解析其實(shí)就是按照 HTML 的規(guī)則解析的。可以打開(kāi) 杭州天氣 在開(kāi)發(fā)者模式中(F12),看一下頁(yè)面的元素分布。
在 main 方法中調(diào)用:
- if __name__ == '__main__':
- url ='http://www.weather.com.cn/weather/101210101.shtml'
- html = getContent(url) # 獲取網(wǎng)頁(yè)信息
- result = getData(html) # 解析網(wǎng)頁(yè)信息,拿到需要的數(shù)據(jù)
- print('my frist python file')
數(shù)據(jù)寫(xiě)入excel
現(xiàn)在我們已經(jīng)在 Python 中拿到了想要的數(shù)據(jù),對(duì)于這些數(shù)據(jù)我們可以先存放起來(lái),比如把數(shù)據(jù)寫(xiě)入 csv 中。
定義一個(gè) writeDate 方法:
- import csv #導(dǎo)入包
- def writeData(data, name):
- with open(name, 'a', errors='ignore', newline='') as f:
- f_csv = csv.writer(f)
- f_csv.writerows(data)
- print('write_csv success')
在 main 方法中調(diào)用:
- if __name__ == '__main__':
- url ='http://www.weather.com.cn/weather/101210101.shtml'
- html = getContent(url) # 獲取網(wǎng)頁(yè)信息
- result = getData(html) # 解析網(wǎng)頁(yè)信息,拿到需要的數(shù)據(jù)
- writeData(result, 'D:/py_work/venv/Include/weather.csv') #數(shù)據(jù)寫(xiě)入到 csv文檔中
- print('my frist python file')
執(zhí)行之后呢,再指定路徑下就會(huì)多出一個(gè) weather.csv 文件,可以打開(kāi)看一下內(nèi)容。
到這里最簡(jiǎn)單的數(shù)據(jù)抓取--儲(chǔ)存就完成了。
數(shù)據(jù)寫(xiě)入數(shù)據(jù)庫(kù)
因?yàn)橐话闱闆r下都會(huì)把數(shù)據(jù)存儲(chǔ)在數(shù)據(jù)庫(kù)中,所以我們以 mysql 數(shù)據(jù)庫(kù)為例,嘗試著把數(shù)據(jù)寫(xiě)入到我們的數(shù)據(jù)庫(kù)中。
***步創(chuàng)建WEATHER 表:
創(chuàng)建表可以在直接在 mysql 客戶端進(jìn)行操作,也可能用 python 創(chuàng)建表。在這里 我們使用 python 來(lái)創(chuàng)建一張 WEATHER 表。
定義一個(gè) createTable 方法:(之前已經(jīng)導(dǎo)入了 import pymysql 如果沒(méi)有的話需要導(dǎo)入包)
- def createTable():
- # 打開(kāi)數(shù)據(jù)庫(kù)連接
- db = pymysql.connect("localhost", "zww", "960128", "test")
- # 使用 cursor() 方法創(chuàng)建一個(gè)游標(biāo)對(duì)象 cursor
- cursor = db.cursor()
- # 使用 execute() 方法執(zhí)行 SQL 查詢
- cursor.execute("SELECT VERSION()")
- # 使用 fetchone() 方法獲取單條數(shù)據(jù).
- data = cursor.fetchone()
- print("Database version : %s " % data) # 顯示數(shù)據(jù)庫(kù)版本(可忽略,作為個(gè)栗子)
- # 使用 execute() 方法執(zhí)行 SQL,如果表存在則刪除
- cursor.execute("DROP TABLE IF EXISTS WEATHER")
- # 使用預(yù)處理語(yǔ)句創(chuàng)建表
- sql = """CREATE TABLE WEATHER (
- w_id int(8) not null primary key auto_increment,
- w_date varchar(20) NOT NULL ,
- w_detail varchar(30),
- w_temperature_low varchar(10),
- w_temperature_high varchar(10)) DEFAULT CHARSET=utf8""" # 這里需要注意設(shè)置編碼格式,不然中文數(shù)據(jù)無(wú)法插入
- cursor.execute(sql)
- # 關(guān)閉數(shù)據(jù)庫(kù)連接
- db.close()
- print('create table success')
在 main 方法中調(diào)用:
- if __name__ == '__main__':
- url ='http://www.weather.com.cn/weather/101210101.shtml'
- html = getContent(url) # 獲取網(wǎng)頁(yè)信息
- result = getData(html) # 解析網(wǎng)頁(yè)信息,拿到需要的數(shù)據(jù)
- writeData(result, 'D:/py_work/venv/Include/weather.csv') #數(shù)據(jù)寫(xiě)入到 csv文檔中
- createTable() #表創(chuàng)建一次就好了,注意
- print('my frist python file')
執(zhí)行之后去檢查一下數(shù)據(jù)庫(kù),看一下 weather 表是否創(chuàng)建成功了。
第二步批量寫(xiě)入數(shù)據(jù)至 WEATHER 表:
定義一個(gè) insertData 方法:
- def insert_data(datas):
- # 打開(kāi)數(shù)據(jù)庫(kù)連接
- db = pymysql.connect("localhost", "zww", "960128", "test")
- # 使用 cursor() 方法創(chuàng)建一個(gè)游標(biāo)對(duì)象 cursor
- cursor = db.cursor()
- try:
- # 批量插入數(shù)據(jù)
- cursor.executemany('insert into WEATHER(w_id, w_date, w_detail, w_temperature_low, w_temperature_high) value(null, %s,%s,%s,%s)', datas)
- # sql = "INSERT INTO WEATHER(w_id,
- # w_date, w_detail, w_temperature)
- # VALUES (null, '%s','%s','%s')" %
- # (data[0], data[1], data[2])
- # cursor.execute(sql) #單條數(shù)據(jù)寫(xiě)入
- # 提交到數(shù)據(jù)庫(kù)執(zhí)行
- db.commit()
- except Exception as e:
- print('插入時(shí)發(fā)生異常' + e)
- # 如果發(fā)生錯(cuò)誤則回滾
- db.rollback()
- # 關(guān)閉數(shù)據(jù)庫(kù)連接
- db.close()
在 main 方法中調(diào)用:
- if __name__ == '__main__':
- url ='http://www.weather.com.cn/weather/101210101.shtml'
- html = getContent(url) # 獲取網(wǎng)頁(yè)信息
- result = getData(html) # 解析網(wǎng)頁(yè)信息,拿到需要的數(shù)據(jù)
- writeData(result, 'D:/py_work/venv/Include/weather.csv') #數(shù)據(jù)寫(xiě)入到 csv文檔中
- # createTable() #表創(chuàng)建一次就好了,注意
- insertData(result) #批量寫(xiě)入數(shù)據(jù)
- print('my frist python file')
檢查:執(zhí)行這段 Python 語(yǔ)句后,看一下數(shù)據(jù)庫(kù)是否有寫(xiě)入數(shù)據(jù)。有的話就大功告成了。
全部代碼看這里:
- # 導(dǎo)入相關(guān)聯(lián)的包
- import requests
- import time
- import random
- import socket
- import http.client
- import pymysql
- from bs4 import BeautifulSoup
- import csv
- def getContent(url , data = None):
- header={
- 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
- 'Accept-Encoding': 'gzip, deflate, sdch',
- 'Accept-Language': 'zh-CN,zh;q=0.8',
- 'Connection': 'keep-alive',
- 'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.235'
- } # request 的請(qǐng)求頭
- timeout = random.choice(range(80, 180))
- while True:
- try:
- rep = requests.get(url,headers = header,timeout = timeout) #請(qǐng)求url地址,獲得返回 response 信息
- rep.encoding = 'utf-8'
- break
- except socket.timeout as e: # 以下都是異常處理
- print( '3:', e)
- time.sleep(random.choice(range(8,15)))
- except socket.error as e:
- print( '4:', e)
- time.sleep(random.choice(range(20, 60)))
- except http.client.BadStatusLine as e:
- print( '5:', e)
- time.sleep(random.choice(range(30, 80)))
- except http.client.IncompleteRead as e:
- print( '6:', e)
- time.sleep(random.choice(range(5, 15)))
- print('request success')
- return rep.text # 返回的 Html 全文
- def getData(html_text):
- final = []
- bs = BeautifulSoup(html_text, "html.parser") # 創(chuàng)建BeautifulSoup對(duì)象
- body = bs.body #獲取body
- data = body.find('div',{'id': '7d'})
- ul = data.find('ul')
- li = ul.find_all('li')
- for day in li:
- temp = []
- date = day.find('h1').string
- temp.append(date) #添加日期
- inf = day.find_all('p')
- weather = inf[0].string #天氣
- temp.append(weather)
- temperature_highest = inf[1].find('span').string #***溫度
- temperature_low = inf[1].find('i').string # ***溫度
- temp.append(temperature_highest)
- temp.append(temperature_low)
- final.append(temp)
- print('getDate success')
- return final
- def writeData(data, name):
- with open(name, 'a', errors='ignore', newline='') as f:
- f_csv = csv.writer(f)
- f_csv.writerows(data)
- print('write_csv success')
- def createTable():
- # 打開(kāi)數(shù)據(jù)庫(kù)連接
- db = pymysql.connect("localhost", "zww", "960128", "test")
- # 使用 cursor() 方法創(chuàng)建一個(gè)游標(biāo)對(duì)象 cursor
- cursor = db.cursor()
- # 使用 execute() 方法執(zhí)行 SQL 查詢
- cursor.execute("SELECT VERSION()")
- # 使用 fetchone() 方法獲取單條數(shù)據(jù).
- data = cursor.fetchone()
- print("Database version : %s " % data) # 顯示數(shù)據(jù)庫(kù)版本(可忽略,作為個(gè)栗子)
- # 使用 execute() 方法執(zhí)行 SQL,如果表存在則刪除
- cursor.execute("DROP TABLE IF EXISTS WEATHER")
- # 使用預(yù)處理語(yǔ)句創(chuàng)建表
- sql = """CREATE TABLE WEATHER (
- w_id int(8) not null primary key auto_increment,
- w_date varchar(20) NOT NULL ,
- w_detail varchar(30),
- w_temperature_low varchar(10),
- w_temperature_high varchar(10)) DEFAULT CHARSET=utf8"""
- cursor.execute(sql)
- # 關(guān)閉數(shù)據(jù)庫(kù)連接
- db.close()
- print('create table success')
- def insertData(datas):
- # 打開(kāi)數(shù)據(jù)庫(kù)連接
- db = pymysql.connect("localhost", "zww", "960128", "test")
- # 使用 cursor() 方法創(chuàng)建一個(gè)游標(biāo)對(duì)象 cursor
- cursor = db.cursor()
- try:
- # 批量插入數(shù)據(jù)
- cursor.executemany('insert into WEATHER(w_id, w_date, w_detail, w_temperature_low, w_temperature_high) value(null, %s,%s,%s,%s)', datas)
- # 提交到數(shù)據(jù)庫(kù)執(zhí)行
- db.commit()
- except Exception as e:
- print('插入時(shí)發(fā)生異常' + e)
- # 如果發(fā)生錯(cuò)誤則回滾
- db.rollback()
- # 關(guān)閉數(shù)據(jù)庫(kù)連接
- db.close()
- print('insert data success')
- if __name__ == '__main__':
- url ='http://www.weather.com.cn/weather/101210101.shtml'
- html = getContent(url) # 獲取網(wǎng)頁(yè)信息
- result = getData(html) # 解析網(wǎng)頁(yè)信息,拿到需要的數(shù)據(jù)
- writeData(result, 'D:/py_work/venv/Include/weather.csv') #數(shù)據(jù)寫(xiě)入到 csv文檔中
- # createTable() #表創(chuàng)建一次就好了,注意
- insertData(result) #批量寫(xiě)入數(shù)據(jù)
- print('my frist python file')