当前位置: 首页 > 科技观察

Python入门仅需20分钟,从安装到数据抓取入库如此简单

时间:2023-03-18 19:35:15 科技观察

基于大众对Python的赞誉和欣赏,作为一名Java从业者,看完Python书籍后,决定成为蟒蛇脑粉。作为一个合格的脑残粉(标题党ノ?ω?)ノ),为了开发我的线下,我将详细介绍Python的安装到开发工具的简单介绍,并编写一个程序来抓取天气信息数据以及保存到数据库示例。(这篇文章适合完全不懂Python的小白。)有时间的话强烈推荐跟着看,因为介绍的真的很详细。源码、视频、书籍、习题等资料私信小编011、Python安装2、PyCharm(ide)安装3、抓取天气信息4、数据写入excel5、数据写入数据库1、Python安装和下载Python:官网地址:https://www.python.org/选择下载然后选择你的电脑系统。小编是Windows系统,所以选择2.Pycharm安装下载PyCharm:官网地址:http://www.jetbrains.com/pycharm/免费版可能缺少一些功能,所以不推荐,所以这里我们选择下载企业版。安装PyCharm后,可能需要输入邮箱地址或激活码,才能获得免费激活码打开:http://idea.lanyus.com/3。抓取天气信息我们准备抓取的数据:杭州天气信息,杭州天气可以先看看这个网站。实现数据抓取的逻辑:使用python请求url,返回相应的html信息。我们解析html得到我们需要的数据。(很简单的逻辑)第一步:创建一个Python文件,写第一段Python代码if__name__=='__main__':url='http://www.weather.com.cn/weather/101210101.shtml'print('myfristpythonfile')这段代码类似于Java中的Main方法。可以直接右击选择运行。第二步:请求RULpython的强大之处在于它有大量的模块(类似Java的jar包)可以直接使用。我们需要安装一个request模块:File-Setting-Product-ProductInterpreter如上图点击+号安装Python模块。顺便安装一个beautifulSoup4和pymysql模块。beautifulSoup4模块用于解析html,可以将HTML字符串对象化。pymysql模块用于连接mysql数据库。相关模块安装完成后,就可以愉快的敲代码了。定义一个getContent方法:#导入关联包importrequestsimporttimeimportrandomimportsocketimporthttp.clientimportpymysqlfrombs4importBeautifulSoupdefgetContent(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(WindowsNT6.3;WOW64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/43.0.235'}#requestrequestheadertimeout=random.choice(range(80,180))whileTrue:try:rep=requests.get(url,headers=header,timeout=timeout)#请求url地址,得到返回的响应信息rep.encoding='utf-8'breakexceptsocket.timeoutase:#下面是异常处理print('3:',e)time.sleep(random.choice(range(8,15)))exceptsocket.errorase:print('4:',e)time.sleep(random.choice(range(20,60))))除了http.client.BadStatusLinease:print('5:',e)time.sleep(random.choice(range(30,80)))excepthttp.client.IncompleteReadase:print('6:',e)time.sleep(random.choice(range(5,15)))print('requestsuccess')returnrep.text#在main方法中调用返回的Html全文:if__name__=='__main__':url='http://www.weather.com.cn/weather/101210101.shtml'html=getContent(url)#调用获取网页信息print('myfristpythonfile')第三步:分析页面数据定义一个getData方法:defgetData(html_text):final=[]bs=BeautifulSoup(html_text,"html.parser")#CreateBeautifulSoupobjectbody=bs.body#Getbodydata=body.find('div',{'id':'7d'})ul=data.find('ul')li=ul.find_all('li')fordayinli:temp=[]date=day.find('h1').stringtemp.append(date)#添加日期inf=day.find_all('p')weather=inf[0].string#Weathertemp.append(weather)temperature_highest=inf[1].find('span').string#***温度temperature_low=inf[1].find('i').string#***temperaturetemp.append(temperature_low)    temp.append(temperature_highest)final.append(temp)print('getDatesuccess')returnfinal上面的分析其实是按照HTML的规则来分析的。您可以在开发者模式(F12)下打开杭州天气,查看页面的元素分布。在main方法中调用:if__name__=='__main__':url='http://www.weather.com.cn/weather/101210101.shtml'html=getContent(url)#获取网页信息result=getData(html)#分析网页信息,得到需要的数据print('myfristpythonfile')并将数据写入excel现在我们已经在Python中得到了想要的数据,我们可以先把这些数据存储起来,比如把数据写入csv。定义一个writeDate方法:importcsv#importpackagedefwriteData(data,name):withopen(name,'a',errors='ignore',newline='')asf:f_csv=csv.writer(f)f_csv.writerows(data)print('write_csvsuccess')在main方法中调用:if__name__=='__main__':url='http://www.weather.com.cn/weather/101210101.shtml'html=getContent(url)#Get网页信息result=getData(html)#解析网页信息,得到需要的数据writeData(result,'D:/py_work/venv/Include/weather.csv')#将数据写入csv文件print('myfristpythonfile')执行后在指定路径下会多出一个weather.csv文件,打开可以看到里面的内容。最简单的数据抓取到这里——存储就完成了。将数据写入数据库因为数据一般都存储在数据库中,所以我们以mysql数据库为例,尝试将数据写入到我们的数据库中。第一步是创建WEATHER表:创建表可以直接在mysql客户端操作,也可以使用python创建表。这里我们使用python创建一个WEATHER表。定义一个createTable方法:(importpymysql之前已经导入,如果没有,需要导入包)defcreateTable():#打开数据库连接db=pymysql.connect("localhost","zww","960128","test")#使用cursor()方法创建游标对象cursorcursor=db.cursor()#使用execute()方法执行SQL查询cursor.execute("SELECTVERSION()")#使用fetchone()获取单条数据的方法.data=cursor.fetchone()print("Databaseversion:%s"%data)#显示数据库版本(忽略不计,举个栗子)#使用execute()方法执行SQL,如果表存在则删除cursor.execute("DROPTABLEIFEXISTSWEATHER")#使用预设处理语句创建表sql="""CREATETABLEWEATHER(w_idint(8)notnullprimarykeyauto_increment,w_datevarchar(20)NOTNULL,w_detailvarchar(30),w_temperature_lowvarchar(10)),w_temperature_highvarchar(10))DEFAULTCHARSET=utf8"""#这里需要注意设置编码格式,否则不能输入中文数据nsertedcursor.execute(sql)#关闭数据库连接db.close()  print('createtablesuccess')在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('myfristpythonfile')后查看数据库执行,查看天气表是否创建成功第二步,批量向WEATHER表写入数据:定义一个insertData方法:definesert_data(datas):#打开数据库连接db=pymysql.connect("localhost","zww","960128","test")#使用cursor()方法创建游标对象cursorcursor=db.cursor()try:#批量插入数据cursor.executemany('insertintoWEATHER(w_id,w_date,w_detail,w_temperature_low,w_temperature_high)value(null,%s,%s,%s,%s)',datas)#sql="INSERTINTOWEATHER(w_id,#w_date,w_detail,w_temperature)#VALUES(null,'%s','%s','%s')"%#(data[0],data[1],data[2])#cursor.execute(sql)#写入单条数据#提交到数据库执行db.commit()exceptExceptionase:print('插入时出现异常'+e)#如果出错则回滚db.rollback()#关闭数据库连接main方法中调用db.close():if__name__=='__main__':url='http://www.weather.com.cn/weather/101210101.shtml'html=getContent(url)#获取网页信息result=getData(html)#分析网页信息,获取requireddatawriteData(result,'D:/py_work/venv/Include/weather.csv')#数据写入到csv文件#createTable()#创建一次表,注意insertData(result)#写入数据到batchesprint('myfristpythonfile')检查:执行完这条Python语句后,检查数据库是否有写入数据。如果有,你就完成了。查看所有代码:#导入相关包importrequestsimporttimeimportrandomimportsocketimporthttp.clientiportpymysqlfrombs4importBeautifulSoupimportcsvdefgetContent(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(WindowsNT6.3;WOW64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/43.0.235'}#requestrequestheadertimeout=random.choice(range(80,180))whileTrue:try:rep=requests.get(url,headers=header,timeout=timeout)#请求url地址,获取返回的响应信息rep.encoding='utf-8'breakexceptsocket.timeoutase:#下面是异常处理print('3:',e)time.sleep(random.choice(range(8,15)))exceptsocket.errorase:print('4:',e)time.sleep(random.choice(range(20,60))))除了http.client.BadStatusLinease:print('5:',e)time.sleep(random.choice(range(30,80)))excepthttp.client.IncompleteReadase:print('6:',e)time.sleep(random.choice(range(5,15)))print('requestsuccess')returnrep.text#returnedHtml全文defgetData(html_text):final=[]bs=BeautifulSoup(html_text,"html.parser")#createBeautifulSoupobjectbody=bs.body#getbodydata=body.find('div',{'id':'7d'})ul=data.find('ul')li=ul.find_all('li')fordayinli:temp=[]date=day.find('h1')。stringtemp.append(date)#adddateinf=day.find_all('p')weather=inf[0].string#weathertemp.append(weather)temperature_highest=inf[1].find('span').字符串#***温度temperature_low=inf[1].find('i').string#***temperaturetemp.append(temperature_highest)temp.append(temperature_low)final.append(temp)print('getDatesuccess')returnfinaldefwriteData(数据,名称):withopen(名称,'a',错误='忽略',换行='')asf:f_csv=csv.writer(f)f_csv.writerows(数据)打印('write_csvsuccess')defcreateTable():#打开数据库连接db=pymysql.connect("localhost","zww","960128","test")#使用cursor()方法创建游标对象cursorcursor=db.cursor()#使用execute()方法执行SQL查询cursor.execute("SELECTVERSION()")#使用fetchone()方法获取单条数据.data=cursor.fetchone()print("Databaseversion:%s"%data)#显示数据库版本(可以忽略,举个栗子)#使用execute()方法执行SQL,如果表存在则删除cursor.execute("DROPTABLEIFEXISTSWEATHER")#使用Prepared语句创建表sql="""CREATETABLEWEATHER(w_idint(8)notnullprimarykeyauto_increment,w_datevarchar(20)NOTNULL,w_detailvarchar(30),w_temperature_lowvarchar(10),w_temperature_highvarchar(10))DEFAULTCHARSET=utf8"""cursor.execute(sql)#关闭数据库连接db.close()print('createtablesuccess')definsertData(datas):#打开数据库连接db=pymysql.connect("localhost","zww","960128","test")#使用cursor()方法创建游标对象cursorcursor=db.cursor()try:#批量插入数据cursor.executemany('insertintoWEATHER(w_id,w_date,w_detail,w_temperature_low,w_temperature_high)value(null,%s,%s,%s,%s)',datas)#提交给数据库执行db.commit()exceptExceptionase:print('插入时发生异常'+e)#出错回滚发生db.rollback()#关闭数据库连接db.close()print('insertdatasuccess')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')#将数据写入csvfile在#createTable()#表创建一次,注意insertData(result)#批量写入数据print('myfristpythonfile')