python爬虫之静态网页——全国空气质量指数(AQI)爬取

首先爬取地址:http://www.air-level.com/

利用的python库,最近最流行的requests,BeautifulSoup。

requests:用于下载html

BeautifulSoup:用于解析

下面开始分析:要获取所有城市的aqi,就要进入每个城市的单独链接,而这些链接可以从主页中获取

打开主网页,查看源代码,可以看到,所有的城市链接都在id=‘citylist’里面

把所有链接爬下来存在一个列表里面,然后依次爬取每个城市的单个链接,附代码:

def get_all_city():    # 爬取城市链接
    url = "http://www.air-level.com"
    try:
        kv = {'user-agent': 'Mozilla/5.0'}  # 伪装成浏览器,headers
        r = requests.get(url, headers=kv)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
    except:
        print("爬取城市链接失败")
    demo = r.text
    soup = BeautifulSoup(demo, "html.parser")
    time = soup.find('h4').string
    print(time)
    for it in soup.find(id="citylist").children:
        if isinstance(it, bs4.element.Tag):   # 检测it的类型,得是一个bs4.element.Tag类型
            for its in it.find_all('a'):
                clist.append(its.get('href'))  # 加入列表当中去
                cnlist.append(its.string)

之后就是每个城市的单独链接的信息爬取,以北京为例,查看源代码可知:

附爬取每个城市代码:

def get_one_page(city):   # 获得HTML 爬取城市信息
    url = "http://www.air-level.com"+city
    if city in cwlink:
        aqilist.append("异常链接")
    else:
        try:
            kv = {'user-agent': 'Mozilla/5.0'}  # 伪装成浏览器,headers
            r = requests.get(url, headers=kv)
            r.raise_for_status()
            r.encoding = r.apparent_encoding
        except:
            print("爬取失败")
        demo = r.text
        soup = BeautifulSoup(demo, "html.parser")
        s = soup.find("span")
        aqilist.append(s.string)

但是在爬取的过程中会发现问题,有的一些城市网站用浏览器打不开,也就爬取不了,所以要做处理,

在上面可以看到,本人用cwlist存储了所有异常链接,跳过去,不爬取。

附完整代码:

import requests
from bs4 import BeautifulSoup
import bs4

aqilist = []   # 储存城市AQI
clist = []     # 储存城市链接
cnlist = []    # 储存城市名字
cwlink = ["/air/changdudiqu/", "/air/kezilesuzhou/", "/air/linzhidiqu/", "/air/rikazediqu/",
          "/air/shannandiqu/", "/air/simao/", "/air/xiangfan/", "/air/yilihasake/"]   # 异常链接


def get_one_page(city):   # 获得HTML 爬取城市信息
    url = "http://www.air-level.com"+city
    if city in cwlink:
        aqilist.append("异常链接")
    else:
        try:
            kv = {'user-agent': 'Mozilla/5.0'}  # 伪装成浏览器,headers
            r = requests.get(url, headers=kv)
            r.raise_for_status()
            r.encoding = r.apparent_encoding
        except:
            print("爬取失败")
        demo = r.text
        soup = BeautifulSoup(demo, "html.parser")
        s = soup.find("span")
        aqilist.append(s.string)


def get_all_city():    # 爬取城市链接
    url = "http://www.air-level.com"
    try:
        kv = {'user-agent': 'Mozilla/5.0'}  # 伪装成浏览器,headers
        r = requests.get(url, headers=kv)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
    except:
        print("爬取城市链接失败")
    demo = r.text
    soup = BeautifulSoup(demo, "html.parser")
    time = soup.find('h4').string
    print(time)
    for it in soup.find(id="citylist").children:
        if isinstance(it, bs4.element.Tag):   # 检测it的类型,得是一个bs4.element.Tag类型
            for its in it.find_all('a'):
                clist.append(its.get('href'))  # 加入列表当中去
                cnlist.append(its.string)


def main():
    get_all_city()
    print("共爬取了{}个城市".format(len(clist)))
    for it in range(len(clist)):
        get_one_page(clist[it])
        print("{} {}".format(cnlist[it], aqilist[it]))


main()

简单的静态爬取就实现了

爬取空气质量检测网的部分城市的历年每天质量数据 思路----------------------------------------- 从某城市的空气质量网页获取某市每月的链接,再爬取每个月的表格数据。连云港市:https://www.aqistudy.cn/historydata/daydata.php?city=连云港 连云港2014年5月的空气质量:https://www.aqistudy.cn/historydata/daydata.php?city=连云港&month=2014-05 遇到的问题----------------------------------------- 获取的网页中的表格数据隐藏,尝试requests无法获取。判断可能是动态加载的网页 尝试----------------------------------------- 1. 通过XHR,js查找隐藏数据的加载网页,没有找到。 2. 使用phantomjs.get() result=pd.read_html ,可以获得隐藏的表格数据,但是并不稳定,只是偶尔出现加载的表格数据,无法大规模的获取 解决方法----------------------------------------- 查找资料得知这个网站的表格数据在Console里的items中, 使用selenium的webdriver.firefox(),driver.execute_script("return items") 数据可获得。 仍遇到的问题:----------------------------------------- 爬取一个网页可获得数据,但是连续的获取网页,会出现两个错误。 1.Message: ReferenceError: items is not defined 2.connection refused 解决方法: 1.connection refused问题,可能是网页开太多,使用driver.quit() 2. 如果 execute_script 还是出错,可尝试pd.read_html获取信息。之前用phantomjs获取的时候输出空的表格,可能由于加载不够,用 Waite直到table出现之后再获取网页 Element=wait.until(EC.element_to_be_clickable((By.XPATH,"/html/body/div[3]/div[1]/div[1]/table/tbody"))) 3.之后出现偶尔出现输出为空,使用循环,如果输出表格为空,再重新获取。 if len(result)>1: filename = str(month) + '.xls' result.to_excel('E:\python\案例程序\data\\' + filename) print('成功存入'+filename) driver.quit() else: driver.quit() return getdata(monthhref,month)
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值