全国空气质量指数爬取


一、主题式网络爬虫设计方案
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