基於大衆對Python的大肆吹捧和讚揚,做爲一名Java從業人員,我本着批判與好奇的心態買了本python方面的書《毫無障礙學Python》。僅僅看了書前面一小部分的我......決定作一名python的腦殘粉。html
做爲一名合格的腦殘粉(標題黨 (ノ◕ω◕)ノ),爲了發展個人下線,接下來我會詳細的介紹 Python 的安裝 到開發工具的簡單介紹,並編寫一個抓取天氣信息數據並存儲到數據庫的例子。(這篇文章適用於徹底不瞭解Python的小白超超超快速入門)python
若是有時間的話,強烈建議跟着一塊兒操做一遍,由於介紹的真的很詳細了。mysql
Python 安裝web
下載 Python: 官網地址: https://www.python.org/sql
選擇你但願下載的版本(均可以的),還有是否64位,選擇下載的文件類型時,推薦下載安裝包,由於在安裝的時候回自動給你配環境路徑。(在下載的時候你能夠去下載 python 的 開發工具 PyCharm,獲取去簡單瞭解一下 Python)數據庫
安裝時須要注意的是:勾選 Add Python x.x to Pathapp
安裝好以後,打開cmd,輸入python,若是出現提示,則完成。dom
PyCharm 安裝socket
下載 PyCharm : 官網地址:http://www.jetbrains.com/pycharm/ide
免費版本的能夠會有部分功能缺失,因此不推薦,因此這裏咱們選擇下載企業版。
安裝好 PyCharm,首次打開可能須要你 輸入郵箱 或者 輸入激活碼,獲取激活碼
對於 PyCharm 的基本使用,能夠簡單看一下 這篇博客
抓取天氣信息
Python 的基礎語法推薦在網上看些教程:菜鳥教程
Python的詳細學習仍是須要些時間的。若是有其餘語言經驗的,能夠暫時跟着我來寫一個簡單的例子。
咱們計劃抓取的數據:杭州的天氣信息,杭州天氣 能夠先看一下這個網站。
實現數據抓取的邏輯:使用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 模塊了。搜索 requests 模塊(有 s 噢),點擊 Install。
咱們順便再安裝一個 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')
Python 的安裝到數據抓取、存儲到這就所有完成了。固然只是最簡單的入門,若是還對 Python 有濃厚興趣的話,但願能夠系統性的學習。