zoukankan      html  css  js  c++  java
  • 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()

    简单的静态爬取就实现了

  • 相关阅读:
    遍历二维数组
    冒泡跟扫描共用
    1.8作业
    1.7作业
    1.5作业
    百文百鸡 水仙花数 百马百担
    for循环输出九九乘法表
    循环语句
    1.4作业
    07、找出1-99之间的同构数
  • 原文地址:https://www.cnblogs.com/horken/p/10706160.html
Copyright © 2011-2022 走看看