【Python入门只需20分钟】从安装到数据抓取、存储原来这么简单
2018-08-23 10:28
911 查看
基于大众对Python的大肆吹捧和赞赏,作为一名Java从业人员,我本着批判与好奇的心态买了本python方面的书《毫无障碍学Python》。仅仅看了书前面一小部分的我......决定做一名python的脑残粉。
作为一名合格的脑残粉(标题党 (ノ◕ω◕)ノ),为了发展我的下线,接下来我会详细的介绍 Python 的安装 到开发工具的简单介绍,并编写一个抓取天气信息数据并存储到数据库的例子。(这篇文章适用于完全不了解Python的小白超超超快速入门)
如果有时间的话,强烈建议跟着一起操作一遍,因为介绍的真的很详细了。
- Python 安装
- PyCharm(ide) 安装
- 抓取天气信息
- 数据写入excel
- 数据写入数据库
Python 安装
下载 Python: 官网地址: https://www.python.org/
# 导入相关联的包 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')View Code
Python 的安装到数据抓取、存储到这就全部完成了。当然只是最简单的入门,如果还对 Python 有浓厚兴趣的话,希望可以系统性的学习。
相关文章推荐
- python scrapy对抓取数据后的存储 sqilte3的安装
- 原来从移动硬盘全新安装win7这么简单
- Python学习入门基础教程(learning Python)--5.7 Python文件数据记录存储与处理
- python 抓取腾讯微博数据并做简单的分析
- Python进行数据科学工作的简单入门教程
- Grid或者DataTable中数据导出为Excel原来这么简单
- 原来DELPHI里面实现数据列表框的列排序是这么简单?
- Python使用shelve模块实现简单数据存储的方法
- 利用python中的pyquery库简单的抓取数据
- python采用requests库模拟登录和抓取数据的简单示例
- 举例简单讲解Python中的数据存储模块shelve的用法
- ubuntu下安装mesa原来也这么简单...,不知道clutter怎么样。
- Android入门——数据存储之SQLite详解与简单应用
- 一个简单的使用python抓取网页中的水文数据的程序
- Python窗口开发环境boa-constructor安装简介与简单入门
- 举例简单讲解Python中的数据存储模块shelve的用法
- XML:简单后台数据存储入门
- 将Python中的数据存储到系统本地的简单方法
- Python开源抓取框架简单介绍,以及安装(ubuntu)常见问题解决
- python 抓取腾讯微博数据并做简单的分析 .