自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Python入門只需20分鐘,從安裝到數(shù)據(jù)抓取、存儲(chǔ)原來這么簡(jiǎn)單

開發(fā) 后端
作為一名合格的腦殘粉,為了發(fā)展我的下線,接下來我會(huì)詳細(xì)的介紹Python的安裝到開發(fā)工具的簡(jiǎn)單介紹,并編寫一個(gè)抓取天氣信息數(shù)據(jù)并儲(chǔ)存到數(shù)據(jù)庫的例子。

[[256751]]

 

基于大眾對(duì)Python的大肆吹捧和贊賞,作為一名Java從業(yè)人員,看了Python的書籍之后,決定做一名python的腦殘粉。

作為一名合格的腦殘粉(標(biāo)題黨ノ◕ω◕)ノ),為了發(fā)展我的下線,接下來我會(huì)詳細(xì)的介紹Python的安裝到開發(fā)工具的簡(jiǎn)單介紹,并編寫一個(gè)抓取天氣信息數(shù)據(jù)并儲(chǔ)存到數(shù)據(jù)庫的例子。(這篇文章適用于完全不了解Python的小白超超超快速入門)

如果有時(shí)間的話,強(qiáng)烈建議跟著一起操作一遍,因?yàn)榻榻B的真的很詳細(xì)了。

源碼視頻書籍練習(xí)題等資料可以私信小編01獲取

1、Python 安裝

2、PyCharm(ide) 安裝

3、抓取天氣信息

4、數(shù)據(jù)寫入excel

5、數(shù)據(jù)寫入數(shù)據(jù)庫

1、Python安裝

下載 Python: 官網(wǎng)地址: https://www.python.org/ 選擇download 再選擇你電腦系統(tǒng),小編是Windows系統(tǒng)的 所以就選擇

Python入門只需20分鐘,從安裝到數(shù)據(jù)抓取、存儲(chǔ)原來這么簡(jiǎn)單

 

 

Python入門只需20分鐘,從安裝到數(shù)據(jù)抓取、存儲(chǔ)原來這么簡(jiǎn)單

 

 

Python入門只需20分鐘,從安裝到數(shù)據(jù)抓取、存儲(chǔ)原來這么簡(jiǎn)單

 

 

2、Pycharm安裝

下載 PyCharm : 官網(wǎng)地址:http://www.jetbrains.com/pycharm/

Python入門只需20分鐘,從安裝到數(shù)據(jù)抓取、存儲(chǔ)原來這么簡(jiǎn)單

 

 

免費(fèi)版本的可以會(huì)有部分功能缺失,所以不推薦,所以這里我們選擇下載企業(yè)版。

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

獲取免費(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 文件

Python入門只需20分鐘,從安裝到數(shù)據(jù)抓取、存儲(chǔ)原來這么簡(jiǎn)單

 

 

寫***段Python代碼

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

這段代碼類似于 Java 中的 Main 方法??梢灾苯邮髽?biāo)右鍵,選擇 Run。

Python入門只需20分鐘,從安裝到數(shù)據(jù)抓取、存儲(chǔ)原來這么簡(jiǎn)單

第二步:請(qǐng)求RUL

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

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

Python入門只需20分鐘,從安裝到數(shù)據(jù)抓取、存儲(chǔ)原來這么簡(jiǎn)單

 

Python入門只需20分鐘,從安裝到數(shù)據(jù)抓取、存儲(chǔ)原來這么簡(jiǎn)單

 

點(diǎn)擊如上圖的 + 號(hào),就可以安裝 Python 模塊了。搜索

Python入門只需20分鐘,從安裝到數(shù)據(jù)抓取、存儲(chǔ)原來這么簡(jiǎn)單

 

 

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

Python入門只需20分鐘,從安裝到數(shù)據(jù)抓取、存儲(chǔ)原來這么簡(jiǎn)單

Python入門只需20分鐘,從安裝到數(shù)據(jù)抓取、存儲(chǔ)原來這么簡(jiǎn)單

 

相關(guān)的模塊都安裝之后,就可以開心的敲代碼了。

定義一個(gè) getContent 方法:

  1. # 導(dǎo)入相關(guān)聯(lián)的包 
  2. import requests 
  3. import time 
  4. import random 
  5. import socket 
  6. import http.client 
  7. import pymysql 
  8. from bs4 import BeautifulSoup 
  9. def getContent(url , data = None): 
  10.  header={ 
  11.  'Accept''text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'
  12.  'Accept-Encoding''gzip, deflate, sdch'
  13.  'Accept-Language''zh-CN,zh;q=0.8'
  14.  'Connection''keep-alive'
  15.  'User-Agent''Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.235' 
  16.  } # request 的請(qǐng)求頭 
  17.  timeout = random.choice(range(80, 180)) 
  18.  while True
  19.  try: 
  20.  rep = requests.get(url,headers = header,timeout = timeout) #請(qǐng)求url地址,獲得返回 response 信息 
  21.  rep.encoding = 'utf-8' 
  22.  break 
  23.  except socket.timeout as e: # 以下都是異常處理 
  24.  print( '3:', e) 
  25.  time.sleep(random.choice(range(8,15))) 
  26.  except socket.error as e: 
  27.  print( '4:', e) 
  28.  time.sleep(random.choice(range(20, 60))) 
  29.  except http.client.BadStatusLine as e: 
  30.  print( '5:', e) 
  31.  time.sleep(random.choice(range(30, 80))) 
  32.  except http.client.IncompleteRead as e: 
  33.  print( '6:', e) 
  34.  time.sleep(random.choice(range(5, 15))) 
  35.  print('request success'
  36.  return rep.text # 返回的 Html 全文 

在 main 方法中調(diào)用:

  1. if __name__ == '__main__'
  2.  url ='http://www.weather.com.cn/weather/101210101.shtml' 
  3.  html = getContent(url) # 調(diào)用獲取網(wǎng)頁信息 
  4.  print('my frist python file'

第三步:分析頁面數(shù)據(jù)

定義一個(gè) getData 方法:

  1. def getData(html_text): 
  2.  final = [] 
  3.  bs = BeautifulSoup(html_text, "html.parser") # 創(chuàng)建BeautifulSoup對(duì)象 
  4.  body = bs.body #獲取body 
  5.  data = body.find('div',{'id''7d'}) 
  6.  ul = data.find('ul'
  7.  li = ul.find_all('li'
  8.  for day in li: 
  9.  temp = [] 
  10.  date = day.find('h1').string 
  11.  temp.append(date) #添加日期 
  12.  inf = day.find_all('p'
  13.  weather = inf[0].string #天氣 
  14.  temp.append(weather) 
  15.  temperature_highest = inf[1].find('span').string #***溫度 
  16.  temperature_low = inf[1].find('i').string # ***溫度 
  17.  temp.append(temperature_low) 
  18.      temp.append(temperature_highest) 
  19.  final.append(temp
  20.  print('getDate success'
  21.  return final 

上面的解析其實(shí)就是按照 HTML 的規(guī)則解析的??梢源蜷_ 杭州天氣 在開發(fā)者模式中(F12),看一下頁面的元素分布。

Python入門只需20分鐘,從安裝到數(shù)據(jù)抓取、存儲(chǔ)原來這么簡(jiǎn)單

 

在 main 方法中調(diào)用:

  1. if __name__ == '__main__'
  2.  url ='http://www.weather.com.cn/weather/101210101.shtml' 
  3.  html = getContent(url) # 獲取網(wǎng)頁信息 
  4.  result = getData(html) # 解析網(wǎng)頁信息,拿到需要的數(shù)據(jù) 
  5.  print('my frist python file'

數(shù)據(jù)寫入excel

現(xiàn)在我們已經(jīng)在 Python 中拿到了想要的數(shù)據(jù),對(duì)于這些數(shù)據(jù)我們可以先存放起來,比如把數(shù)據(jù)寫入 csv 中。

定義一個(gè) writeDate 方法:

  1. import csv #導(dǎo)入包 
  2. def writeData(data, name): 
  3.  with open(name'a', errors='ignore', newline=''as f: 
  4.  f_csv = csv.writer(f) 
  5.  f_csv.writerows(data) 
  6.  print('write_csv success'

在 main 方法中調(diào)用:

  1. if __name__ == '__main__'
  2.  url ='http://www.weather.com.cn/weather/101210101.shtml' 
  3.  html = getContent(url) # 獲取網(wǎng)頁信息 
  4.  result = getData(html) # 解析網(wǎng)頁信息,拿到需要的數(shù)據(jù) 
  5.  writeData(result, 'D:/py_work/venv/Include/weather.csv') #數(shù)據(jù)寫入到 csv文檔中 
  6.  print('my frist python file'

執(zhí)行之后呢,再指定路徑下就會(huì)多出一個(gè) weather.csv 文件,可以打開看一下內(nèi)容。

Python入門只需20分鐘,從安裝到數(shù)據(jù)抓取、存儲(chǔ)原來這么簡(jiǎn)單

 

Python入門只需20分鐘,從安裝到數(shù)據(jù)抓取、存儲(chǔ)原來這么簡(jiǎn)單

 

到這里最簡(jiǎn)單的數(shù)據(jù)抓取--儲(chǔ)存就完成了。

數(shù)據(jù)寫入數(shù)據(jù)庫

因?yàn)橐话闱闆r下都會(huì)把數(shù)據(jù)存儲(chǔ)在數(shù)據(jù)庫中,所以我們以 mysql 數(shù)據(jù)庫為例,嘗試著把數(shù)據(jù)寫入到我們的數(shù)據(jù)庫中。

***步創(chuàng)建WEATHER 表:

創(chuàng)建表可以在直接在 mysql 客戶端進(jìn)行操作,也可能用 python 創(chuàng)建表。在這里 我們使用 python 來創(chuàng)建一張 WEATHER 表。

定義一個(gè) createTable 方法:(之前已經(jīng)導(dǎo)入了 import pymysql 如果沒有的話需要導(dǎo)入包)

  1. def createTable(): 
  2.  # 打開數(shù)據(jù)庫連接 
  3.  db = pymysql.connect("localhost""zww""960128""test"
  4.  # 使用 cursor() 方法創(chuàng)建一個(gè)游標(biāo)對(duì)象 cursor 
  5.  cursor = db.cursor() 
  6.  # 使用 execute() 方法執(zhí)行 SQL 查詢 
  7.  cursor.execute("SELECT VERSION()"
  8.  # 使用 fetchone() 方法獲取單條數(shù)據(jù). 
  9.  data = cursor.fetchone() 
  10.  print("Database version : %s " % data) # 顯示數(shù)據(jù)庫版本(可忽略,作為個(gè)栗子) 
  11.  # 使用 execute() 方法執(zhí)行 SQL,如果表存在則刪除 
  12.  cursor.execute("DROP TABLE IF EXISTS WEATHER"
  13.  # 使用預(yù)處理語句創(chuàng)建表 
  14.  sql = """CREATE TABLE WEATHER ( 
  15.  w_id int(8) not null primary key auto_increment,  
  16.  w_date varchar(20) NOT NULL , 
  17.  w_detail varchar(30), 
  18.  w_temperature_low varchar(10), 
  19.  w_temperature_high varchar(10)) DEFAULT CHARSET=utf8""" # 這里需要注意設(shè)置編碼格式,不然中文數(shù)據(jù)無法插入 
  20.  cursor.execute(sql) 
  21.  # 關(guān)閉數(shù)據(jù)庫連接 
  22.  db.close() 
  23.   print('create table success'

在 main 方法中調(diào)用:

  1. if __name__ == '__main__'
  2.  url ='http://www.weather.com.cn/weather/101210101.shtml' 
  3.  html = getContent(url) # 獲取網(wǎng)頁信息 
  4.  result = getData(html) # 解析網(wǎng)頁信息,拿到需要的數(shù)據(jù) 
  5.  writeData(result, 'D:/py_work/venv/Include/weather.csv') #數(shù)據(jù)寫入到 csv文檔中 
  6.  createTable() #表創(chuàng)建一次就好了,注意 
  7.  print('my frist python file'

執(zhí)行之后去檢查一下數(shù)據(jù)庫,看一下 weather 表是否創(chuàng)建成功了。

Python入門只需20分鐘,從安裝到數(shù)據(jù)抓取、存儲(chǔ)原來這么簡(jiǎn)單

 

第二步批量寫入數(shù)據(jù)至 WEATHER 表:

定義一個(gè) insertData 方法:

  1. def insert_data(datas): 
  2.  # 打開數(shù)據(jù)庫連接 
  3.  db = pymysql.connect("localhost""zww""960128""test"
  4.  # 使用 cursor() 方法創(chuàng)建一個(gè)游標(biāo)對(duì)象 cursor 
  5.  cursor = db.cursor() 
  6.  try: 
  7.  # 批量插入數(shù)據(jù) 
  8.  cursor.executemany('insert into WEATHER(w_id, w_date, w_detail, w_temperature_low, w_temperature_high) value(null, %s,%s,%s,%s)', datas) 
  9.  # sql = "INSERT INTO WEATHER(w_id,  
  10.  # w_date, w_detail, w_temperature)  
  11.  # VALUES (null'%s','%s','%s')" %  
  12.  # (data[0], data[1], data[2]) 
  13.  # cursor.execute(sql) #單條數(shù)據(jù)寫入 
  14.  # 提交到數(shù)據(jù)庫執(zhí)行 
  15.  db.commit() 
  16.  except Exception as e: 
  17.  print('插入時(shí)發(fā)生異常' + e) 
  18.  # 如果發(fā)生錯(cuò)誤則回滾 
  19.  db.rollback() 
  20.  # 關(guān)閉數(shù)據(jù)庫連接 
  21.  db.close() 

在 main 方法中調(diào)用:

  1. if __name__ == '__main__'
  2.  url ='http://www.weather.com.cn/weather/101210101.shtml' 
  3.  html = getContent(url) # 獲取網(wǎng)頁信息 
  4.  result = getData(html) # 解析網(wǎng)頁信息,拿到需要的數(shù)據(jù) 
  5.  writeData(result, 'D:/py_work/venv/Include/weather.csv') #數(shù)據(jù)寫入到 csv文檔中 
  6.  # createTable() #表創(chuàng)建一次就好了,注意 
  7.  insertData(result) #批量寫入數(shù)據(jù) 
  8.  print('my frist python file'

檢查:執(zhí)行這段 Python 語句后,看一下數(shù)據(jù)庫是否有寫入數(shù)據(jù)。有的話就大功告成了。

Python入門只需20分鐘,從安裝到數(shù)據(jù)抓取、存儲(chǔ)原來這么簡(jiǎn)單

 

全部代碼看這里:

  1. # 導(dǎo)入相關(guān)聯(lián)的包 
  2. import requests 
  3. import time 
  4. import random 
  5. import socket 
  6. import http.client 
  7. import pymysql 
  8. from bs4 import BeautifulSoup 
  9. import csv 
  10. def getContent(url , data = None): 
  11.  header={ 
  12.  'Accept''text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'
  13.  'Accept-Encoding''gzip, deflate, sdch'
  14.  'Accept-Language''zh-CN,zh;q=0.8'
  15.  'Connection''keep-alive'
  16.  'User-Agent''Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.235' 
  17.  } # request 的請(qǐng)求頭 
  18.  timeout = random.choice(range(80, 180)) 
  19.  while True
  20.  try: 
  21.  rep = requests.get(url,headers = header,timeout = timeout) #請(qǐng)求url地址,獲得返回 response 信息 
  22.  rep.encoding = 'utf-8' 
  23.  break 
  24.  except socket.timeout as e: # 以下都是異常處理 
  25.  print( '3:', e) 
  26.  time.sleep(random.choice(range(8,15))) 
  27.  except socket.error as e: 
  28.  print( '4:', e) 
  29.  time.sleep(random.choice(range(20, 60))) 
  30.  except http.client.BadStatusLine as e: 
  31.  print( '5:', e) 
  32.  time.sleep(random.choice(range(30, 80))) 
  33.  except http.client.IncompleteRead as e: 
  34.  print( '6:', e) 
  35.  time.sleep(random.choice(range(5, 15))) 
  36.  print('request success'
  37.  return rep.text # 返回的 Html 全文 
  38. def getData(html_text): 
  39.  final = [] 
  40.  bs = BeautifulSoup(html_text, "html.parser") # 創(chuàng)建BeautifulSoup對(duì)象 
  41.  body = bs.body #獲取body 
  42.  data = body.find('div',{'id''7d'}) 
  43.  ul = data.find('ul'
  44.  li = ul.find_all('li'
  45.  for day in li: 
  46.  temp = [] 
  47.  date = day.find('h1').string 
  48.  temp.append(date) #添加日期 
  49.  inf = day.find_all('p'
  50.  weather = inf[0].string #天氣 
  51.  temp.append(weather) 
  52.  temperature_highest = inf[1].find('span').string #***溫度 
  53.  temperature_low = inf[1].find('i').string # ***溫度 
  54.  temp.append(temperature_highest) 
  55.  temp.append(temperature_low) 
  56.  final.append(temp
  57.  print('getDate success'
  58.  return final 
  59. def writeData(data, name): 
  60.  with open(name'a', errors='ignore', newline=''as f: 
  61.  f_csv = csv.writer(f) 
  62.  f_csv.writerows(data) 
  63.  print('write_csv success'
  64. def createTable(): 
  65.  # 打開數(shù)據(jù)庫連接 
  66.  db = pymysql.connect("localhost""zww""960128""test"
  67.  # 使用 cursor() 方法創(chuàng)建一個(gè)游標(biāo)對(duì)象 cursor 
  68.  cursor = db.cursor() 
  69.  # 使用 execute() 方法執(zhí)行 SQL 查詢 
  70.  cursor.execute("SELECT VERSION()"
  71.  # 使用 fetchone() 方法獲取單條數(shù)據(jù). 
  72.  data = cursor.fetchone() 
  73.  print("Database version : %s " % data) # 顯示數(shù)據(jù)庫版本(可忽略,作為個(gè)栗子) 
  74.  # 使用 execute() 方法執(zhí)行 SQL,如果表存在則刪除 
  75.  cursor.execute("DROP TABLE IF EXISTS WEATHER"
  76.  # 使用預(yù)處理語句創(chuàng)建表 
  77.  sql = """CREATE TABLE WEATHER ( 
  78.  w_id int(8) not null primary key auto_increment,  
  79.  w_date varchar(20) NOT NULL , 
  80.  w_detail varchar(30), 
  81.  w_temperature_low varchar(10), 
  82.  w_temperature_high varchar(10)) DEFAULT CHARSET=utf8""
  83.  cursor.execute(sql) 
  84.  # 關(guān)閉數(shù)據(jù)庫連接 
  85.  db.close() 
  86.  print('create table success'
  87. def insertData(datas): 
  88.  # 打開數(shù)據(jù)庫連接 
  89.  db = pymysql.connect("localhost""zww""960128""test"
  90.  # 使用 cursor() 方法創(chuàng)建一個(gè)游標(biāo)對(duì)象 cursor 
  91.  cursor = db.cursor() 
  92.  try: 
  93.  # 批量插入數(shù)據(jù) 
  94.  cursor.executemany('insert into WEATHER(w_id, w_date, w_detail, w_temperature_low, w_temperature_high) value(null, %s,%s,%s,%s)', datas) 
  95.  # 提交到數(shù)據(jù)庫執(zhí)行 
  96.  db.commit() 
  97.  except Exception as e: 
  98.  print('插入時(shí)發(fā)生異常' + e) 
  99.  # 如果發(fā)生錯(cuò)誤則回滾 
  100.  db.rollback() 
  101.  # 關(guān)閉數(shù)據(jù)庫連接 
  102.  db.close() 
  103.  print('insert data success'
  104. if __name__ == '__main__'
  105.  url ='http://www.weather.com.cn/weather/101210101.shtml' 
  106.  html = getContent(url) # 獲取網(wǎng)頁信息 
  107.  result = getData(html) # 解析網(wǎng)頁信息,拿到需要的數(shù)據(jù) 
  108.  writeData(result, 'D:/py_work/venv/Include/weather.csv') #數(shù)據(jù)寫入到 csv文檔中 
  109.  # createTable() #表創(chuàng)建一次就好了,注意 
  110.  insertData(result) #批量寫入數(shù)據(jù) 
  111.  print('my frist python file')  

 

責(zé)任編輯:龐桂玉 來源: 今日頭條
相關(guān)推薦

2017-01-05 14:16:28

連接池數(shù)據(jù)代碼

2016-09-13 20:58:41

MySQ基礎(chǔ)入門Sql

2020-11-27 10:34:01

HTTPHTTPS模型

2022-09-30 15:46:26

Babel編譯器插件

2016-08-03 16:01:47

GitLinux開源

2013-09-17 09:49:29

程序集讀懂程序編程

2009-07-09 17:43:30

Chrome OS截圖Chrome操作系統(tǒng)截Chrome

2021-11-19 11:16:29

Git命令Linux

2023-09-11 08:25:57

PythonPyQt

2023-09-08 07:54:01

TkinterPython

2015-01-05 09:35:54

云計(jì)算應(yīng)用程序開發(fā)

2021-04-19 05:42:51

Mmap文件系統(tǒng)

2022-06-17 08:05:28

Grafana監(jiān)控儀表盤系統(tǒng)

2019-08-29 11:10:07

PythonVimLinux

2012-07-10 01:22:32

PythonPython教程

2013-06-27 09:41:19

LuaLua語言Lua語言快速入門

2023-11-01 14:49:07

2016-03-21 11:09:52

Tableau/大數(shù)據(jù)

2023-06-07 08:27:10

Docker容器

2021-01-03 17:30:10

3D人像ARVR
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)