首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

通过python分析我国城市污染

今天在看天气的时候,突然想把全国各个城市的PM2.5值都获取过来,然后进分类(按网站上的分类为:优、良、轻度污染、中度污染、重度污染、严重污染),看看现在我国哪一类占比比较多。

那先说一下实现这个效果需要用到的功能:你需要安装包beatufulsoup、matplotlib、requests、itchat(这个看你出来成果后需要往微信上发送)。

那下面我直接上我的代码了:

def getHtml(url):

html=requests.get(url)

if html.status_code==200:

html.encoding=html.apparent_encoding

manage_html(html.text)

else:

print("该网站不能爬虫")

def manage_html(html):

soup=BeautifulSoup(html,"html.parser")

ulist1=[]

ulist2=[]

ulist3=[]

ulist4=[]

kq={"优":0,"良":0,"轻度污染":0,"中度污染":0,"重度污染":0,"严重污染":0}

for i in soup.find_all(class_ = "pjadt_ranknum"):

ulist1.append(i.get_text())

for i in soup.find_all(class_ = "pjadt_location"):

ulist2.append(i.get_text())

for i in soup.find_all(class_ = "pjadt_sheng"):

ulist3.append(i.get_text())

for i in soup.find_all(class_ = "pjadt_aqi"):

ulist4.append(i.get_text())

for i in range(1,359):

if int(ulist4[i])

kq['优']=kq['优']+1

elif int(ulist4[i])>50 and int(ulist4[i])

kq['良']=kq['良']+1

elif int(ulist4[i])>100 and int(ulist4[i])

kq['轻度污染']=kq['轻度污染']+1

elif int(ulist4[i])>150 and int(ulist4[i])

kq['中度污染']=kq['中度污染']+1

elif int(ulist4[i])>200 and int(ulist4[i])

kq['重度污染']=kq['重度污染']+1

elif int(ulist4[i])>300:

kq['严重污染']=kq['严重污染']+1

plt.figure(figsize=(10,15))

labels = [u'优',u'中度污染',u'轻度污染',u'重度污染',u'良',u'严重污染']

sizes = [kq['优'],kq['中度污染'],kq['轻度污染'],kq['重度污染'],kq['良'],kq['严重污染']]

colors = ['blue','red','gray','purple','lightskyblue','black']

patches,l_text,p_text = plt.pie(sizes,labels=labels,colors=colors,

labeldistance = 1.1,autopct = '%3.1f%%',shadow = False,

startangle = 90,pctdistance = 0.6)

plt.axis('equal')

plt.legend()

filePath="d:\\11.jpg"

plt.savefig(filePath)

plt.show()

bot=Bot(cache_path=True)

my_friend=bot.friends().search("OnlyOne")[0]

my_friend.send_image(filePath)

aa=getHtml(url1)

主要这项技术本身不算太难,用到的知识点是:字典、列表、抓取网页数据的预处理及查找网页内容的规律。

那放一下最后实现的效果图:

我感觉一定有其他方便的方法,欢迎其他人指点,同时程序员们就不要吐槽,我是业余爱好,同时也是代码的搬运工。

  • 发表于:
  • 原文链接https://kuaibao.qq.com/s/20181209G0XPDE00?refer=cp_1026
  • 腾讯「腾讯云开发者社区」是腾讯内容开放平台帐号(企鹅号)传播渠道之一,根据《腾讯内容开放平台服务协议》转载发布内容。
  • 如有侵权,请联系 cloudcommunity@tencent.com 删除。

扫码

添加站长 进交流群

领取专属 10元无门槛券

私享最新 技术干货

扫码加入开发者社群
领券