Python入門只需20分鐘,從安裝到資料抓取、儲存原來這麼簡單
基於大眾對Python的大肆吹捧和讚賞,作為一名Java從業人員,看了Python的書籍之後,決定做一名python的腦殘粉。
作為一名合格的腦殘粉(標題黨ノ◕ω◕)ノ),為了發展我的下線,接下來我會詳細的介紹Python的安裝到開發工具的簡單介紹,並編寫一個抓取天氣資訊資料並儲存到資料庫的例子。(這篇文章適用於完全不瞭解Python的小白超超超快速入門)
如果有時間的話,強烈建議跟著一起操作一遍,因為介紹的真的很詳細了。
原始碼視訊書籍練習題等資料可以私信小編01獲取
1、Python 安裝
2、PyCharm(ide) 安裝
3、抓取天氣資訊
4、資料寫入excel
5、資料寫入資料庫
1、Python安裝
下載 Python: 官網地址: https://www.python.org/ 選擇download 再選擇你電腦系統,小編是Windows系統的 所以就選擇
2、Pycharm安裝
下載 PyCharm : 官網地址:http://www.jetbrains.com/pycharm/
免費版本的可以會有部分功能缺失,所以不推薦,所以這裡我們選擇下載企業版。
安裝好 PyCharm,首次開啟可能需要你 輸入郵箱 或者 輸入啟用碼
獲取免費的啟用碼:http://idea.lanyus.com/
3、抓取天氣資訊
我們計劃抓取的資料:杭州的天氣資訊,杭州天氣 可以先看一下這個網站。
實現資料抓取的邏輯:使用python 請求 URL,會返回對應的 HTML 資訊,我們解析 html,獲得自己需要的資料。(很簡單的邏輯)
第一步:建立 Python 檔案
寫第一段Python程式碼
if __name__ == '__main__': url = 'http://www.weather.com.cn/weather/101210101.shtml' print('my frist python file')
這段程式碼類似於 Java 中的 Main 方法。可以直接滑鼠右鍵,選擇 Run。
第二步:請求RUL
python 的強大之處就在於它有大量的模組(類似於Java 的 jar 包)可以直接拿來使用。
我們需要安裝一個 request 模組: File - Setting - Product - Product Interpreter
點選如上圖的 + 號,就可以安裝 Python 模組了。搜尋
我們順便再安裝一個 beautifulSoup4 和 pymysql 模組,beautifulSoup4 模組是用來解析 html 的,可以物件化 HTML 字串。pymysql 模組是用來連線 mysql 資料庫使用的。
相關的模組都安裝之後,就可以開心的敲程式碼了。
定義一個 getContent 方法:
# 匯入相關聯的包 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 的請求頭 timeout = random.choice(range(80, 180)) while True: try: rep = requests.get(url,headers = header,timeout = timeout) #請求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 方法中呼叫:
if __name__ == '__main__': url ='http://www.weather.com.cn/weather/101210101.shtml' html = getContent(url) # 呼叫獲取網頁資訊 print('my frist python file')
第三步:分析頁面資料
定義一個 getData 方法:
def getData(html_text): final = [] bs = BeautifulSoup(html_text, "html.parser") # 建立BeautifulSoup物件 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
上面的解析其實就是按照 HTML 的規則解析的。可以開啟 杭州天氣 在開發者模式中(F12),看一下頁面的元素分佈。
在 main 方法中呼叫:
if __name__ == '__main__': url ='http://www.weather.com.cn/weather/101210101.shtml' html = getContent(url) # 獲取網頁資訊 result = getData(html) # 解析網頁資訊,拿到需要的資料 print('my frist python file')
資料寫入excel
現在我們已經在 Python 中拿到了想要的資料,對於這些資料我們可以先存放起來,比如把資料寫入 csv 中。
定義一個 writeDate 方法:
import csv #匯入包 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 方法中呼叫:
if __name__ == '__main__': url ='http://www.weather.com.cn/weather/101210101.shtml' html = getContent(url) # 獲取網頁資訊 result = getData(html) # 解析網頁資訊,拿到需要的資料 writeData(result, 'D:/py_work/venv/Include/weather.csv') #資料寫入到 csv文件中 print('my frist python file')
執行之後呢,再指定路徑下就會多出一個 weather.csv 檔案,可以開啟看一下內容。
到這裡最簡單的資料抓取--儲存就完成了。
資料寫入資料庫
因為一般情況下都會把資料儲存在資料庫中,所以我們以 mysql 資料庫為例,嘗試著把資料寫入到我們的資料庫中。
第一步建立WEATHER 表:
建立表可以在直接在 mysql 客戶端進行操作,也可能用 python 建立表。在這裡 我們使用 python 來建立一張 WEATHER 表。
定義一個 createTable 方法:(之前已經匯入了 import pymysql 如果沒有的話需要匯入包)
def createTable(): # 開啟資料庫連線 db = pymysql.connect("localhost", "zww", "960128", "test") # 使用 cursor() 方法建立一個遊標物件 cursor cursor = db. cursor() # 使用 execute() 方法執行 SQL 查詢 cursor. execute("SELECT VERSION()") # 使用 fetchone() 方法獲取單條資料. data = cursor.fetchone() print("Database version : %s " % data) # 顯示資料庫版本(可忽略,作為個栗子) # 使用 execute() 方法執行 SQL,如果表存在則刪除 cursor. execute("DROP TABLE IF EXISTS WEATHER") # 使用預處理語句建立表 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) # 關閉資料庫連線 db.close() print('create table success')
在 main 方法中呼叫:
if __name__ == '__main__': url ='http://www.weather.com.cn/weather/101210101.shtml' html = getContent(url) # 獲取網頁資訊 result = getData(html) # 解析網頁資訊,拿到需要的資料 writeData(result, 'D:/py_work/venv/Include/weather.csv') #資料寫入到 csv文件中 createTable() #表建立一次就好了,注意 print('my frist python file')
執行之後去檢查一下資料庫,看一下 weather 表是否建立成功了。
第二步批量寫入資料至 WEATHER 表:
定義一個 insertData 方法:
def insert_data(datas): # 開啟資料庫連線 db = pymysql.connect("localhost", "zww", "960128", "test") # 使用 cursor() 方法建立一個遊標物件 cursor cursor = db. cursor() try: # 批量插入資料 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) #單條資料寫入 # 提交到資料庫執行 db.commit() except Exception as e: print('插入時發生異常' + e) # 如果發生錯誤則回滾 db.rollback() # 關閉資料庫連線 db.close()
在 main 方法中呼叫:
if __name__ == '__main__': url ='http://www.weather.com.cn/weather/101210101.shtml' html = getContent(url) # 獲取網頁資訊 result = getData(html) # 解析網頁資訊,拿到需要的資料 writeData(result, 'D:/py_work/venv/Include/weather.csv') #資料寫入到 csv文件中 # createTable() #表建立一次就好了,注意 insertData(result) #批量寫入資料 print('my frist python file')
檢查:執行這段 Python 語句後,看一下資料庫是否有寫入資料。有的話就大功告成了。
全部程式碼看這裡:
# 匯入相關聯的包 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 的請求頭 timeout = random.choice(range(80, 180)) while True: try: rep = requests.get(url,headers = header,timeout = timeout) #請求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") # 建立BeautifulSoup物件 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(): # 開啟資料庫連線 db = pymysql.connect("localhost", "zww", "960128", "test") # 使用 cursor() 方法建立一個遊標物件 cursor cursor = db. cursor() # 使用 execute() 方法執行 SQL 查詢 cursor. execute("SELECT VERSION()") # 使用 fetchone() 方法獲取單條資料. data = cursor.fetchone() print("Database version : %s " % data) # 顯示資料庫版本(可忽略,作為個栗子) # 使用 execute() 方法執行 SQL,如果表存在則刪除 cursor. execute("DROP TABLE IF EXISTS WEATHER") # 使用預處理語句建立表 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) # 關閉資料庫連線 db.close() print('create table success') def insertData(datas): # 開啟資料庫連線 db = pymysql.connect("localhost", "zww", "960128", "test") # 使用 cursor() 方法建立一個遊標物件 cursor cursor = db. cursor() try: # 批量插入資料 cursor.executemany('insert into WEATHER(w_id, w_date, w_detail, w_temperature_low, w_temperature_high) value(null, %s,%s,%s,%s)', datas) # 提交到資料庫執行 db.commit() except Exception as e: print('插入時發生異常' + e) # 如果發生錯誤則回滾 db.rollback() # 關閉資料庫連線 db.close() print('insert data success') if __name__ == '__main__': url ='http://www.weather.com.cn/weather/101210101.shtml' html = getContent(url) # 獲取網頁資訊 result = getData(html) # 解析網頁資訊,拿到需要的資料 writeData(result, 'D:/py_work/venv/Include/weather.csv') #資料寫入到 csv文件中 # createTable() #表建立一次就好了,注意 insertData(result) #批量寫入資料 print('my frist python file')
【責任編輯:龐桂玉 TEL:(010)68476606】