全國空氣質量指數爬取


一、主題式網絡爬蟲設計方案
1.主題式網絡爬蟲名稱:
       爬取全國空氣質量指數
2.主題式網絡爬蟲爬取的內容與數據特征分析:主要爬取 全國空氣質量最好城市排名和全國空氣質量最差城市排名
3.主題式網絡爬蟲設計方案概述(包括實現思路與技術難點)
      實現思路為先對網頁源代碼分析,用BeautifulSoup對數據進行清洗,最后通過進行數據可視化。技術難點主要包括爬蟲爬取列表和對數據的清洗以及可視化。
二、主題頁面的結構特征分析
1.主題頁面的結構與特征分析
 
2.Htmls頁面解析
 
3.節點(標簽)查找方法與遍歷方法 find_all

 

 

 三、網絡爬蟲程序設計

1.數據爬取與采集

 1 #導入相關模塊
 2 from sklearn.linear_model import LinearRegression
 3 from matplotlib import  pyplot as plt
 4 import pandas as pd
 5 import numpy as np
 6 import scipy as sp
 7 import seaborn as sns
 8 import requests
 9 from bs4 import BeautifulSoup
10 import bs4
11 
12 ulist=[]
13 ulist_1=[]
14 ulist_2=[]
15 ulist_3=[]
16 ulist_4=[]
17 def getHTMLtext(url):
18     try:
19         rr=requests.get(url,timeout=30,headers=header)
20         r.raise_for_status()
21         r.encoding=r.apparent_encoding
22         return r.text
23     except:
24         return '爬取錯誤'
25 #獲取數據
26 def get_quality(html):
27     soup = BeautifulSoup(html,"html.parser")    #用BeautifulSoup類解析網頁

 

2.對數據進行清洗和處理

 

 

用html的解析器
    a=soup.find_all('table',class_='b',width='300px')
    for i in soup.find_all('table',class_='b',width="300px"):
        ulist_2.append(i.text)
    soup_1=BeautifulSoup(i.text,'html.parser')
    soup_=list(soup_1)
def get_title(html):
    soup = BeautifulSoup(html,"html.parser")    #用BeautifulSoup類解析網頁,采用html的解析器
    for i in soup.find_all('table',class_='b',width="300px"):
        ulist_1.append(i.td.b.string)
#整理獲得內容
def change(ulist_2,ulist_1):
    for i in ulist_2:
        if i in ulist_1:
            ulist_3=ulist_2.remove(i)

4.數據分析與可視化(例如:數據柱形圖、直方圖、散點圖、盒圖、分布圖)(15分)
df=pd.DataFrame(pd.read_csv('全國空氣質量排名2.csv'))
plt.rcParams['font.sans-serif']=['SimHei'] #顯示中文
plt.rcParams['axes.unicode_minus']=False 
g=df['PM25']
h=df.at[輕度污染','PM25']
e=df.at['','PM25']
i=df.at['中度污染','PM25']
j=df.at['重度污染','PM25']
k=df.at['嚴重污染','PM25']
l=[e]
l.append(h)
l.append(i)
l.append(j)
l.append(k)
x=['',輕度污染','中度污染','重度污染','嚴重污染']
plt.figure(figsize=(5,3))
plt.boxplot(l, labels = x)
plt.title('空氣質量等級箱體圖')
plt.legend()
plt.show()

5.根據數據之間的關系,分析兩個變量之間的相關系數,畫出散點圖,並建立變量之間的回歸方程(一元或多元)(10分)。

df['PM2.5'].corre(df['AQI'])
x=df['PM2.5']
y=df['AQI']
def func(p,x):
    a,b,c=p
    return a*x*x+b*x+c
def error(p,x,y,s):
    print(s)
    return fun(p,x)-y
p0=[200,3]
def main():
    plt.figure(figsize=(10,6))
    p0=[200,3,2]
    Para=leastsq(error,p0,args=(x,y))
    a,b,c=Para[0]
    print("a=",a,"b=",b,"c=",c)
    plt.scatter(x,y,color="red",label="Sample Point",linewidth=2) 
main()
x=np.linspace(0,10,1000)
y=a*x*x+b*x+c
plt.plot(x,y,color="orange",label="Fitting Line",linewidth=2)

 

 

6.數據持久化

def data(html, filename):
   file_name=filename+'.csv'
   f=open(file_name,'w')
   f.write('%s\t %s\t %s\t %s\t %s\n'%('排名','city','AQI','quality','PM2.5'))
   f.write('{}\t {}\t {}\t {}\n'.format(ulist_1,ulist_2,ulist_3,ulist_4))

7.將以上各部分的代碼匯總,附上完整程序代碼

 #導入相關模塊
from sklearn.linear_model import LinearRegression
from matplotlib import  pyplot as plt
import pandas as pd
import numpy as np
import scipy as sp
import seaborn as sns
import requests
from bs4 import BeautifulSoup
import bs4

ulist=[]
ulist_1=[]
ulist_2=[]
ulist_3=[]
ulist_4=[]
def getHTMLtext(url):
     try:
         rr=requests.get(url,timeout=30,headers=header)
        r.raise_for_status()
         r.encoding=r.apparent_encoding
         return r.text
     except:
         return '爬取錯誤'
#獲取數據
def get_quality(html):
     soup = BeautifulSoup(html,"html.parser")    #用BeautifulSoup類解析網頁,采
用html的解析器
    a=soup.find_all('table',class_='b',width='300px')
    for i in soup.find_all('table',class_='b',width="300px"):
        ulist_2.append(i.text)
    soup_1=BeautifulSoup(i.text,'html.parser')
    soup_=list(soup_1)
def get_title(html):
    soup = BeautifulSoup(html,"html.parser")    #用BeautifulSoup類解析網頁,采用html的解析器
    for i in soup.find_all('table',class_='b',width="300px"):
        ulist_1.append(i.td.b.string)
#整理獲得內容
def change(ulist_2,ulist_1):
    for i in ulist_2:
        if i in ulist_1:
            ulist_3=ulist_2.remove(i)
df=pd.DataFrame(pd.read_csv('全國空氣質量排名2.csv'))
plt.rcParams['font.sans-serif']=['SimHei'] #顯示中文
plt.rcParams['axes.unicode_minus']=False
g=df['PM25']
h=df.at[輕度污染','PM25']
e=df.at['','PM25']
i=df.at['中度污染','PM25']
j=df.at['重度污染','PM25']
k=df.at['嚴重污染','PM25']
l=[e]
l.append(h)
l.append(i)
l.append(j)
l.append(k)
x=['',輕度污染','中度污染','重度污染','嚴重污染']
plt.figure(figsize=(5,3))
plt.boxplot(l, labels = x)
plt.title('空氣質量等級箱體圖')
plt.legend()
plt.show()

df['PM2.5'].corre(df['AQI']) x=df['PM2.5'] y=df['AQI'] def func(p,x): a,b,c=p return a*x*x+b*x+c def error(p,x,y,s): print(s) return fun(p,x)-y p0=[200,3] def main(): plt.figure(figsize=(10,6)) p0=[200,3,2] Para=leastsq(error,p0,args=(x,y)) a,b,c=Para[0] print("a=",a,"b=",b,"c=",c) plt.scatter(x,y,color="red",label="Sample Point",linewidth=2) main() x=np.linspace(0,10,1000) y=a*x*x+b*x+c plt.plot(x,y,color="orange",linewidth=2)
def data(html, filename):
   file_name=filename+'.csv'
   f=open(file_name,'w')
   f.write('%s\t %s\t %s\t %s\t %s\n'%('排名','city','AQI','quality','PM2.5'))
   f.write('{}\t {}\t {}\t {}\n'.format(ulist_1,ulist_2,ulist_3,ulist_4))

 

四、結論(10分)
1.經過對主題數據的分析與可視化,可以得到哪些結論?PM2.5與AQI成正比,PM2.5越高則AQI越高,空氣質量越差

2.對本次程序設計任務完成的情況做一個簡單的小結。

本來以為自己都學的差不多了 ,但是實際自己動手操作起來,才發現沒有那么簡單,很多東西都要查資料,同時也發現了如CDSN這樣的博客網以及博客園和CDSN都有的眾多文章可以參考,總結前人的經驗補充自己的知識。編程一行還是要不斷學習不斷動手才可以越走越遠,如同逆水行舟不進則退。

 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM