找回密码
 立即注册

扫一扫,访问微社区

QQ登录

只需一步,快速开始

查看: 4359|回复: 0

[代码与实例] 抓取上海气象信息网天气信息

1

主题

1

帖子

1

积分

贫民

积分
1
duocool 发表于 2017-1-4 11:42:13 | 显示全部楼层 |阅读模式
上海天气多变,一般公司还都得备把伞啥的,上海气象信息网(http://www.soweather.com/index.html)是本地权威的天气信息平台。上面有最近5天还有当天的逐小时天气信息。
特别是这个逐小时天气信息对不测之风云特有用,不过当时这网站没啥微信,APP啥的,要看只有去网站上,于是弄个爬虫程序抓之。

tq.JPG

python 2.7环境:
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. import urllib2
  4. from bs4 import BeautifulSoup

  5. html_doc = "http://www.soweather.com/todayweather.html"
  6. page=urllib2.urlopen(html_doc)

  7. soup = BeautifulSoup(page, "html.parser")

  8. #print soup.prettify()

  9. today='\n'+'今日天气'+'\n'
  10. print today.decode('utf-8').encode('gbk','ignore')
  11. todaylist=soup.find(class_="left1a")
  12. todaystr=todaylist.get_text()
  13. print todaystr.encode('gbk','ignore')

  14. fiveday='\n'+'未来五天预报'+'\n'
  15. print fiveday.decode('utf-8').encode('gbk','ignore')
  16. for one in soup(class_="sh5dayb sh5daybborder"):
  17.     today=one.get_text()
  18.     today_str=""
  19.     lineNum=0
  20.     for line in today.splitlines():
  21.         line=line.lstrip()
  22.         if (lineNum==0 or lineNum==5):
  23.             endLine=''
  24.         else:
  25.             endLine='  '
  26.         line=line.rstrip()+endLine
  27.         
  28.         
  29.         today_str=today_str+line
  30.         lineNum=lineNum+1
  31.    
  32.    
  33.     #print today_str.__class__
  34.     print today_str.encode('gbk','ignore')
  35. hour='\n\n'+'逐小时预报'+'\n'
  36. print hour.decode('utf-8').encode('gbk','ignore')

  37. name='时间'+'\t'+'温度'+'\t'+'湿度'+'\t'+'风速'+'\t'+'雨量'+'\t'+'体感'
  38. print name.decode('utf-8').encode('gbk','ignore')


  39. hour_list=soup.find(class_="childta")
  40. ul_list=hour_list('tr')
  41. hour_num=0
  42. for mytext in ul_list:
  43.     mytext=mytext.get_text()
  44.     hour_str=""
  45.     num=0
  46.     for line in mytext.splitlines():
  47.         line=line.rstrip()+'\t'
  48.         if (num==1 or num==6 or num==7 or num==9 or num==10 or num==11):
  49.             hour_str=hour_str+line
  50.         num=num+1
  51.     if (hour_num<>0):
  52.         print hour_str.encode('gbk','ignore')
  53.     hour_num=hour_num+1
  54. raw_input()
复制代码


不过现在这网站上微信,APP都有了,手机弄一个,很方便了
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表