您还未登录! 登录 | 注册 | 帮助  

您的位置: 首页 > 软件开发专栏 > 开发技术 > 正文

Python入门只需20分钟,从安装到数据抓取、存储原来这么简单

发表于:2019-01-30 作者:编程python新视野 来源:今日头条

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代码


  1. if __name__ == '__main__': 
  2.  url = 'http://www.weather.com.cn/weather/101210101.shtml'  
  3.  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 方法:


  1. # 导入相关联的包 
  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 的请求头 
  17.  timeout = random.choice(range(80, 180)) 
  18.  while True: 
  19.  try: 
  20.  rep = requests.get(url,headers = header,timeout = timeout) #请求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 方法中调用:


  1. if __name__ == '__main__': 
  2.  url ='http://www.weather.com.cn/weather/101210101.shtml'
  3.  html = getContent(url) # 调用获取网页信息 
  4.  print('my frist python file') 

第三步:分析页面数据

定义一个 getData 方法:


  1. def getData(html_text): 
  2.  final = [] 
  3.  bs = BeautifulSoup(html_text, "html.parser") # 创建BeautifulSoup对象 
  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 

上面的解析其实就是按照 HTML 的规则解析的。可以打开 杭州天气 在开发者模式中(F12),看一下页面的元素分布。

Python入门只需20分钟,从安装到数据抓取、存储原来这么简单

 

在 main 方法中调用:


  1. if __name__ == '__main__': 
  2.  url ='http://www.weather.com.cn/weather/101210101.shtml'
  3.  html = getContent(url) # 获取网页信息 
  4.  result = getData(html) # 解析网页信息,拿到需要的数据 
  5.  print('my frist python file') 

数据写入excel

现在我们已经在 Python 中拿到了想要的数据,对于这些数据我们可以先存放起来,比如把数据写入 csv 中。

定义一个 writeDate 方法:


  1. import csv #导入包 
  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 方法中调用:


  1. if __name__ == '__main__': 
  2.  url ='http://www.weather.com.cn/weather/101210101.shtml'
  3.  html = getContent(url) # 获取网页信息 
  4.  result = getData(html) # 解析网页信息,拿到需要的数据 
  5.  writeData(result, 'D:/py_work/venv/Include/weather.csv') #数据写入到 csv文档中 
  6.  print('my frist python file') 

执行之后呢,再指定路径下就会多出一个 weather.csv 文件,可以打开看一下内容。

Python入门只需20分钟,从安装到数据抓取、存储原来这么简单

 

Python入门只需20分钟,从安装到数据抓取、存储原来这么简单

 

到这里最简单的数据抓取--储存就完成了。

数据写入数据库

因为一般情况下都会把数据存储在数据库中,所以我们以 mysql 数据库为例,尝试着把数据写入到我们的数据库中。

第一步创建WEATHER 表:

创建表可以在直接在 mysql 客户端进行操作,也可能用 python 创建表。在这里 我们使用 python 来创建一张 WEATHER 表。

定义一个 createTable 方法:(之前已经导入了 import pymysql 如果没有的话需要导入包)


  1. def createTable(): 
  2.  # 打开数据库连接 
  3.  db = pymysql.connect("localhost", "zww", "960128", "test") 
  4.  # 使用 cursor() 方法创建一个游标对象 cursor
  5.  cursor = db.cursor() 
  6.  # 使用 execute() 方法执行 SQL 查询 
  7.  cursor.execute("SELECT VERSION()") 
  8.  # 使用 fetchone() 方法获取单条数据. 
  9.  data = cursor.fetchone() 
  10.  print("Database version : %s " % data) # 显示数据库版本(可忽略,作为个栗子) 
  11.  # 使用 execute() 方法执行 SQL,如果表存在则删除 
  12.  cursor.execute("DROP TABLE IF EXISTS WEATHER") 
  13.  # 使用预处理语句创建表 
  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""" # 这里需要注意设置编码格式,不然中文数据无法插入 
  20.  cursor.execute(sql) 
  21.  # 关闭数据库连接 
  22.  db.close() 
  23. print('create table success') 

在 main 方法中调用:


  1. if __name__ == '__main__': 
  2.  url ='http://www.weather.com.cn/weather/101210101.shtml'
  3.  html = getContent(url) # 获取网页信息 
  4.  result = getData(html) # 解析网页信息,拿到需要的数据 
  5.  writeData(result, 'D:/py_work/venv/Include/weather.csv') #数据写入到 csv文档中 
  6.  createTable() #表创建一次就好了,注意 
  7.  print('my frist python file') 

执行之后去检查一下数据库,看一下 weather 表是否创建成功了。

Python入门只需20分钟,从安装到数据抓取、存储原来这么简单

 

第二步批量写入数据至 WEATHER 表:

定义一个 insertData 方法:


  1. def insert_data(datas): 
  2.  # 打开数据库连接 
  3.  db = pymysql.connect("localhost", "zww", "960128", "test") 
  4.  # 使用 cursor() 方法创建一个游标对象 cursor
  5.  cursor = db.cursor() 
  6.  try: 
  7.  # 批量插入数据 
  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) #单条数据写入 
  14.  # 提交到数据库执行 
  15.  db.commit() 
  16.  except Exception as e: 
  17.  print('插入时发生异常' + e) 
  18.  # 如果发生错误则回滚 
  19.  db.rollback() 
  20.  # 关闭数据库连接 
  21.  db.close() 

在 main 方法中调用:


  1. if __name__ == '__main__': 
  2.  url ='http://www.weather.com.cn/weather/101210101.shtml'
  3.  html = getContent(url) # 获取网页信息 
  4.  result = getData(html) # 解析网页信息,拿到需要的数据 
  5.  writeData(result, 'D:/py_work/venv/Include/weather.csv') #数据写入到 csv文档中 
  6.  # createTable() #表创建一次就好了,注意 
  7.  insertData(result) #批量写入数据 
  8.  print('my frist python file') 

检查:执行这段 Python 语句后,看一下数据库是否有写入数据。有的话就大功告成了。

Python入门只需20分钟,从安装到数据抓取、存储原来这么简单

 

全部代码看这里:


  1. # 导入相关联的包 
  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 的请求头 
  18.  timeout = random.choice(range(80, 180)) 
  19.  while True: 
  20.  try: 
  21.  rep = requests.get(url,headers = header,timeout = timeout) #请求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") # 创建BeautifulSoup对象 
  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.  # 打开数据库连接 
  66.  db = pymysql.connect("localhost", "zww", "960128", "test") 
  67.  # 使用 cursor() 方法创建一个游标对象 cursor
  68.  cursor = db.cursor() 
  69.  # 使用 execute() 方法执行 SQL 查询 
  70.  cursor.execute("SELECT VERSION()") 
  71.  # 使用 fetchone() 方法获取单条数据. 
  72.  data = cursor.fetchone() 
  73.  print("Database version : %s " % data) # 显示数据库版本(可忽略,作为个栗子) 
  74.  # 使用 execute() 方法执行 SQL,如果表存在则删除 
  75.  cursor.execute("DROP TABLE IF EXISTS WEATHER") 
  76.  # 使用预处理语句创建表 
  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.  # 关闭数据库连接 
  85.  db.close() 
  86.  print('create table success') 
  87. def insertData(datas): 
  88.  # 打开数据库连接 
  89.  db = pymysql.connect("localhost", "zww", "960128", "test") 
  90.  # 使用 cursor() 方法创建一个游标对象 cursor
  91.  cursor = db.cursor() 
  92.  try: 
  93.  # 批量插入数据 
  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.  # 提交到数据库执行 
  96.  db.commit() 
  97.  except Exception as e: 
  98.  print('插入时发生异常' + e) 
  99.  # 如果发生错误则回滚 
  100.  db.rollback() 
  101.  # 关闭数据库连接 
  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) # 获取网页信息 
  107.  result = getData(html) # 解析网页信息,拿到需要的数据 
  108.  writeData(result, 'D:/py_work/venv/Include/weather.csv') #数据写入到 csv文档中 
  109.  # createTable() #表创建一次就好了,注意 
  110.  insertData(result) #批量写入数据 
  111.  print('my frist python file')