今天是平安夜,来分享点什么代码呢?就来写一个天气的爬虫程序好了拉。以下为北京的天气爬虫:
# coding=utf-8 ##这句话也是挺重要的呢,因为前面讲过,要想让数据库里显示出中文字符,utf-8是非常好用的
import string, urllib2,re ,sys,os #导入各种库
import MySQLdb<span style="white-space:pre"> </span>#继续导入库
conn=MySQLdb.connect(<span style="white-space:pre"> </span>#此段为链接数据库
host='localhost',
port=3306,
user='root',
passwd='bjtungirc',
db='news',
charset='utf8') #very important!!!!!!
cur=conn.cursor()
def beijing(url): #开始
n=0
m = urllib2.urlopen(url).read() <span style="white-space:pre"> </span>#将天气的源码抓取下来
m2= re.findall('300.3.*?"101010200"/>',m,re.S)<span style="white-space:pre"> </span>#用正则表达式选取有用的信息哦
m3=''.join(m2)<span style="white-space:pre"> </span>#要把m2转化为字符串类型
temp1=re.findall('tem1="(.*?)"',m3,re.S) #取出需要的数据,下面就是取出各种各样的数据,比如最高温度,最低温度等,原理都是一样的,就不赘述了。
temp1=''.join(temp1)
temp2=re.findall('tem2="(.*?)"',m3,re.S)
temp2=''.join(temp2)
tempnow=re.findall('temNow="(.*?)"',m3,re.S)
tempnow=''.join(tempnow)
winddir=re.findall('windDir="(.*?)"',m3,re.S)
winddir=''.join(winddir)
windpow=re.findall('windPower="(.*?)"',m3,re.S)
windpow=''.join(windpow)
windstate=re.findall('windState="(.*?)"',m3,re.S)
windstate=''.join(windstate)
sun=re.findall('state1="(.*?)"',m3,re.S)
sun=''.join(sun)
print temp1,temp2,tempnow,winddir,windpow,windstate,sun #这里是在命令行里输出看一下效果
sqli="replace into weather values(1,'Beijing',%s,%s,%s,%s,%s,%s,%s)" #这里是往数据库里写数据
cur.execute(sqli,(temp2,temp1,tempnow,windstate,winddir,windpow,sun)) #同上
bjurl = 'http://flash.weather.com.cn/wmaps/xml/beijing.xml' #这是url
beijing(bjurl) #调用beijing这个函数
cur.close()<span style="white-space:pre"> </span>#结束数据库的链接
conn.commit()
conn.close()
这个程序有点问题就是堆xml的处理应该可以用更简单的方法。这个在之后应该会进行更新的。人生就是在一点一点的学习中慢慢成长的。平安夜快乐。晚安~