怎样使用爬虫获取新加坡PSI信息( 三 )

流程就是分三步走:打开网页——获取信息——保存信息考虑到每个月天数不同,所以要先计算每个月的天数有的日期会多出PM2.5的信息(下图所示),我的处理是略去怎样使用爬虫获取新加坡PSI信息

运行代码:# -*- coding: utf-8 -*-#新加坡psi 2014-1-1~today 的爬虫import spiders=spider.Spider()#日期year=2015month=3delta=s.timeDelta(year,month)#一个月一个月的抓取print year,month,\u0026#39;strat!\u0026#39;for day in range(1,delta+1): #日期 date=s.handleDate(year,month,day) #网页内容 pageContent=s.getPageContent(date) #获得信息 infos=s.getPageInfos(pageContent)# #保存信息 s.saveAllInfo(infos,date) print day,\u0026#39;/\u0026#39;,delta day+=1print year,month,\u0026#39;end!\u0026#39;运行过程:怎样使用爬虫获取新加坡PSI信息

数据保存的路径:psi/year/month/day.csv合并数据的代码:# -*- coding: utf-8 -*-import osfor yearNum in : listMonth=os.listdir(\u0026#39;psi/\u0026#39;+str(yearNum)+\u0026#39;/\u0026#39;) for monthNum in listMonth: openPath=\u0026#39;psi/\u0026#39;+str(yearNum)+\u0026#39;/\u0026#39;+str(monthNum)+\u0026#39;/\u0026#39; listFileName=os.listdir(openPath) for fileName in listFileName: a=open(openPath+fileName,\u0026#39;r\u0026#39;) content=a.read() a.close() if os.path.exists(u\u0026#39;hebing.csv\u0026#39;): mode=\u0026#39;a\u0026#39; else: mode=\u0026#39;w\u0026#39; b=open(u\u0026#39;hebing.csv\u0026#39;,mode) b.write(content) b.close()嗯,就是这样,献丑啦代码好丑,,,,
■网友
使用爬虫建议看看我们家的产品吧,支持浏览器加载网页数据直接采集,还可以直接导出EXCEL
怎样使用爬虫获取新加坡PSI信息
【怎样使用爬虫获取新加坡PSI信息】


■网友
#!/usr/bin/env python# -*- coding: utf-8 -*-# @Date : 2015-11-10 16:21:59import requestsfrom bs4 import BeautifulSoupurl = \u0026#39;http://www.nea.gov.sg/anti-pollution-radiation-protection/air-pollution-control/psi/historical-psi-readings/year/2014/month/4/day/1\u0026#39;req = requests.get(url)soup = BeautifulSoup(req.text, "html.parser")PSI_infos = soup.find(\u0026#39;table\u0026#39;, class_="text_psinormal").find( \u0026#39;tbody\u0026#39;).find_all(\u0026#39;tr\u0026#39;)for info in PSI_infos: items = info.find_all(\u0026#39;span\u0026#39;, id=True) for item in items: print item.get_text(), print输出:1am 55 54 54 58 54 54-582am 55 54 54 59 54 54-593am 55 55 54 60 55 54-604am 56 55 55 62 55 55-625am 57 55 56 63 56 55-636am 58 56 56 64 56 56-647am 59 57 57 65 57 57-658am 60 57 58 66 58 57-669am 59 57 58 66 59 57-6610am 60 58 58 67 59 58-6711am 60 57 59 67 59 57-6712pm 60 57 58 67 59 57-671pm 59 56 58 67 59 56-672pm 59 56 58 67 59 56-673pm 59 56 57 67 59 56-674pm 58 55 57 66 59 55-665pm 58 55 58 66 59 55-666pm 57 55 57 66 59 55-667pm 57 55 57 66 59 55-668pm 58 56 57 66 59 56-669pm 58 56 57 66 59 56-6610pm 58 56 57 65 58 56-6511pm 58 56 57 65 58 56-6512am 58 55 57 64 58 55-64


推荐阅读