Python命令行实现—查全国7天天气,


为什么要爬天气呢?1.可以练练手2.利用itchat库实现自动回复功能后,把查天气的功能集成起来,实现微信自助查天气功能!

首先,还是相似的套路,我们看看能不能在官网上直接抓包(XHR)来获取一个通用API。然后直接用API查询就OK?在百度搜关键词【天气】或者【南京天气】会跳出对应的网页:http://www.weather.com.cn/weather/101190101.shtml.点进去,可以看到相应城市下一周的天气情况:

再换一个城市上海,我们发现,浏览器地址变为:http://www.weather.com.cn/weather/101020100.shtml。原来101020100这串数字对应着相应城市的代码。我们来分析下页面上XHR请求,看看有没有直接抓包的可能?

经过谷歌浏览器——检查-Networt-XHR-刷新,发现并没有XHR请求,看来我们需要的天气内容和城市代码,可能是包含在页面中经过JS和服务器处理后呈现的.....好吧,尝试失败!

再看一下JS请求,发现太多了,无力去逐一查看!所幸网上有人早已记录下了所有城市对应的城市代码。我把拷贝了一下,存到了本地mysql,数据在百度云上,需要的可以自行下载下,执行SQL即可直接把SQL表和数据一并建好。https://pan.baidu.com/s/1kXaN2Aj 密码是:8y6n。

好了,准备工作做完了,现在思路就很清楚了,全国城市和代码都有了,我们查某个城市的天气,只需要输入城市,就可以从mysql里获取对应的城市代码如:101020100,然后构造相应的url:http://www.weather.com.cn/weather/101190101.shtml就可以查看到对应城市的7天天气了,然而,页面并没有XHR和直接可用的json数据,那我们只能自己动手了——分析网页内容,动手写正则表达式/beautifulSoup/Xpath来提取页面信息,具体内容在此就不赘述了,详见代码就好:

import re 
import pymysql 
import requests 
from bs4 import BeautifulSoup 
 
class SearchWeather(): 
    def __init__(self): 
        self.HEADERS ={ 
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 ''(KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'} 
        self.CONNECTION = pymysql.connect(host='localhost',user='root',password='xxx',db='xxx',charset='utf8',cursorclass=pymysql.cursors.DictCursor) 
 
    def getcityCode(self,cityName): 
        SQL = "SELECT cityCode FROM cityWeather WHERE cityName='%s'" % cityName 
        try: 
            with self.CONNECTION.cursor() as cursor: 
                cursor.execute(SQL) 
                self.CONNECTION.commit() 
                result = cursor.fetchone() 
                return result['cityCode'] 
        except Exception as e: 
            print(repr(e)) 
 
    def getWeather(self,cityCode,cityname): 
        url = 'http://www.weather.com.cn/weather/%s.shtml' % cityCode 
        html = requests.get(url,headers = self.HEADERS) 
        html.encoding='utf-8' 
        soup=BeautifulSoup(html.text,'lxml') 
        weather = "日期      天气    【温度】    风向风力\n" 
        for item in soup.find("div", {'id': '7d'}).find('ul').find_all('li'): 
            date,detail = item.find('h1').string, item.find_all('p') 
            title = detail[0].string 
            templow = detail[1].find("i").string 
            temphigh = detail[1].find('span').string if detail[1].find('span')  else '' 
            wind,direction = detail[2].find('span')['title'], detail[2].find('i').string 
            if temphigh=='': 
                weather += '你好,【%s】今天白天:【%s】,温度:【%s】,%s:【%s】\n' % (cityname,title,templow,wind,direction) 
            else: 
                weather += (date + title + "【" + templow +  "~"+temphigh +'°C】' + wind + direction + "\n") 
        return weather 
 
    def main(self,city): 
        cityCode = self.getcityCode(city) 
        detail = self.getWeather(cityCode,city) 
        print (detail) 
 
if __name__ == "__main__": 
    weather = SearchWeather() 
    weather.main(city=input('请输入城市名称:')) 

代码运行效果如下:

相关内容

    暂无相关文章

评论关闭