从互联网抓取数据有时候也是企业的一个常见的需求,下边测试了从一个网站抓取的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