python3抓取aqi

从互联网抓取数据有时候也是企业的一个常见的需求,下边测试了从一个网站抓取的aqi信息

 

#!/usr/bin/env python
# -*- coding: utf-8 -*-

#import urllib2
#from urllib import parse as urlparse
import urllib.request
import threading
from time import ctime
from bs4 import BeautifulSoup

import pymysql
import sys

# 打开数据库连接
db = pymysql.connect(host="192.168.XX.XX", port=3306, user="test", passwd='123456', db="dbname", charset="utf8")


def getPM25(cityname):
    site = 'http://www.pm25.com/' + cityname + '.html'
    #urllib.request.urlopen()函数用于实现对目标url的访问
    #urllib2.request.urlopen()拿到的数据是response对象,该对象有几个方法:read() , readline() , readlines() , fileno() , close() 
    #直接用urllib.request模块的urlope()获取页面,page的数据格式为bytes类型,需要decode()解码,转换成str类型
    html = urllib.request.urlopen(site)
    #Beautiful Soup是python的一个HTML或XML的解析库,我们可以用它来方便的从网页中提取数据,它拥有强大的API和多样的解析方式
    soup = BeautifulSoup(html,"html.parser")
    city = soup.find(class_ = 'bi_loaction_city')   # 城市名称
    aqi = soup.find("a",{"class","bi_aqiarea_num"})  # AQI指数
    #aqi=str(aqi)
    quality = soup.select(".bi_aqiarea_right span")  # 空气质量等级
    result = soup.find("div",class_ ='bi_aqiarea_bottom')   # 空气质量描述
    print(city.text + u'AQI指数:' + aqi.text + u'\n空气质量:' + quality[0].text + result.text)
    print('*'*20 + ctime() + '*'*20)
    # 使用cursor()方法获取游标对象
    cursor = db.cursor()
    #sql = """insert into TABLE1(CITYNAME)
    #         values('china')"""
    try:
        cursor.execute('insert into TABLE1(CITYNAME,AQI,TEXT1,TEXT2) values("%s","%d","%s","%s")'% (city.text, int(aqi.text),quality[0].text,result.text))
        #cursor.execute('insert into TABLE1(CITYNAME) values("%s")' % (city))
        #cursor.execute(sql)
        # 提交到数据库执行
        db.commit()
    except Exception as e:
        # 如果发生错误
        db.rollback()
        print(e)
        print('----------------------------------')
def one_thread():   # 单线程
    print('One_thread Start: ' + ctime() + '\n')
    getPM25('hefei')
    getPM25('shanghai')
def two_thread():   # 多线程
    print('Two_thread Start: ' + ctime() + '\n')
    threads = []
    t1 = threading.Thread(target=getPM25,args=('hefei',))
    threads.append(t1)
    t2 = threading.Thread(target=getPM25,args=('shanghai',))
    threads.append(t2)
    for t in threads:
        # t.setDaemon(True)
        t.start()
def one_thread_loop():   # 单线程
    print('One_thread Start: ' + ctime() + '\n')
    city_list = ['beijing','shanghai','shenzhen','wuhan']
    for city in city_list:
        getPM25(city)

if __name__ == '__main__':
    #one_thread()
    #print('\n' * 2)
    #two_thread()
    one_thread_loop()
    db.close()

结果:

 

 

One_thread Start: Fri Dec  8 16:44:52 2017

北京AQI指数:53
空气质量:良
PM2.5浓度:21微克/立方米
击败了全国 66% 的城市,目前城市排名 121 

********************Fri Dec  8 16:44:53 2017********************
上海AQI指数:51
空气质量:良
PM2.5浓度:26微克/立方米
击败了全国 69% 的城市,目前城市排名 112 

********************Fri Dec  8 16:44:53 2017********************
深圳AQI指数:62
空气质量:良
PM2.5浓度:43微克/立方米
击败了全国 36% 的城市,目前城市排名 232 

********************Fri Dec  8 16:44:54 2017********************
武汉AQI指数:64
空气质量:良
PM2.5浓度:45微克/立方米
击败了全国 31% 的城市,目前城市排名 249 

********************Fri Dec  8 16:44:55 2017********************

Process finished with exit code 0

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

朝闻道-夕死可矣

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值