Python入門只需20分鐘,從安裝到數據抓取、存儲原來這麼簡單

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系統的 所以就選擇

Python入門只需20分鐘,從安裝到數據抓取、存儲原來這麼簡單


Python入門只需20分鐘,從安裝到數據抓取、存儲原來這麼簡單


Python入門只需20分鐘,從安裝到數據抓取、存儲原來這麼簡單


2、Pycharm安裝

下載 PyCharm : 官網地址:http://www.jetbrains.com/pycharm/

Python入門只需20分鐘,從安裝到數據抓取、存儲原來這麼簡單


免費版本的可以會有部分功能缺失,所以不推薦,所以這裡我們選擇下載企業版。

安裝好 PyCharm,首次打開可能需要你 輸入郵箱 或者 輸入激活碼

獲取免費的激活碼:http://idea.lanyus.com/

3、抓取天氣信息

我們計劃抓取的數據:杭州的天氣信息,杭州天氣 可以先看一下這個網站。

實現數據抓取的邏輯:使用python 請求 URL,會返回對應的 HTML 信息,我們解析 html,獲得自己需要的數據。(很簡單的邏輯)

第一步:創建 Python 文件

Python入門只需20分鐘,從安裝到數據抓取、存儲原來這麼簡單


寫第一段Python代碼

if __name__ == '__main__':
url = 'http://www.weather.com.cn/weather/101210101.shtml'
print('my frist python file')

這段代碼類似於 Java 中的 Main 方法。可以直接鼠標右鍵,選擇 Run。

Python入門只需20分鐘,從安裝到數據抓取、存儲原來這麼簡單


第二步:請求RUL

python 的強大之處就在於它有大量的模塊(類似於Java 的 jar 包)可以直接拿來使用。

我們需要安裝一個 request 模塊: File - Setting - Product - Product Interpreter

Python入門只需20分鐘,從安裝到數據抓取、存儲原來這麼簡單

Python入門只需20分鐘,從安裝到數據抓取、存儲原來這麼簡單

點擊如上圖的 + 號,就可以安裝 Python 模塊了。搜索

Python入門只需20分鐘,從安裝到數據抓取、存儲原來這麼簡單


我們順便再安裝一個 beautifulSoup4 和 pymysql 模塊,beautifulSoup4 模塊是用來解析 html 的,可以對象化 HTML 字符串。pymysql 模塊是用來連接 mysql 數據庫使用的。

Python入門只需20分鐘,從安裝到數據抓取、存儲原來這麼簡單


Python入門只需20分鐘,從安裝到數據抓取、存儲原來這麼簡單

相關的模塊都安裝之後,就可以開心的敲代碼了。

定義一個 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),看一下頁面的元素分佈。

Python入門只需20分鐘,從安裝到數據抓取、存儲原來這麼簡單

在 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 文件,可以打開看一下內容。

Python入門只需20分鐘,從安裝到數據抓取、存儲原來這麼簡單

Python入門只需20分鐘,從安裝到數據抓取、存儲原來這麼簡單

到這裡最簡單的數據抓取--儲存就完成了。

數據寫入數據庫

因為一般情況下都會把數據存儲在數據庫中,所以我們以 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 表是否創建成功了。

Python入門只需20分鐘,從安裝到數據抓取、存儲原來這麼簡單

第二步批量寫入數據至 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 語句後,看一下數據庫是否有寫入數據。有的話就大功告成了。

Python入門只需20分鐘,從安裝到數據抓取、存儲原來這麼簡單

全部代碼看這裡:

# 導入相關聯的包
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')


分享到:


相關文章: