爬天气的一个小爬虫

从新浪爬天气,改url中的城市名即可修改城市

使用bs,requests写的

<pre name="code" class="python">#coding=utf-8
import requests
import re
import argparse
from bs4 import BeautifulSoup

parser = argparse.ArgumentParser()
parser.add_argument('-c','--city',default='hangzhou')
args = parser.parse_args()
city = args.city

url = 'http://weather.sina.com.cn/'+city
response = requests.get(url)
response.encoding = 'utf-8'
soup = BeautifulSoup(response.text,'html.parser')

city = soup.find(class_='slider_ct_name').string.encode('utf-8')
date = []
weather = []
temperature = []

#get date
for item in soup('p',class_='wt_fc_c0_i_date'):
	date.append(unicode(item.string).encode('utf-8'))
#get weather
for item in soup("img", {"class": 'icons0_wt'}):
	weather.append(item['alt'].encode('utf-8'))
#get temperature
for item in soup('p',class_='wt_fc_c0_i_temp'):
	temperature.append(item.string.encode('utf-8'))

txt = ''

txt += city + '10日天气:\n'
for counter in range(10):
	txt += date[counter] +'\t' +'day:' + weather[2*counter] +'\t\t\t'+'nignt:'+weather[2*counter+1]+'\t\t'
	txt += temperature[counter]
	txt +='\n'
print txt

filename = city + '10日天气'+'.txt'
with open(filename,'w') as fp:
	fp.write(txt)
#注意:在晚上使用本爬虫会出现数组越界,原因是今天白天的天气数据已经消失了,所以weather数组实际上只有19个元素,稍稍改动即可
#last modified on 2016.9.25




                
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值