python--爬虫百度天气数据

#coding=utf-8
'''
从百度或者http://www.weather.com.cn获取天气情况

'''
from selenium import webdriver
import time

class BaiduWeather():
    def __init__(self):
        self.query_url = 'http://www.baidu.com/s?wd=%stianqi '
        self.location = 'shenzhen'
        self.dr = webdriver.Firefox()
        self.dr.get(self.total_url)
        
    @property
    def today_css_selectors(self):
        today_main_klass = '.op_weather4_twoicon_today.%s'
        return {
                'temp':today_main_klass %(' op_weather4_twoicon_temp'),
                'weather':today_main_klass %(' op_weather4_twoicon_weath'),
                'wind':today_main_klass%(' op_weather4_twoicon_wind')
                }
    
    @property
    def total_url(self):
        return self.query_url %(self.location)
    
    def get_weather(self,date='today'):
        if date == 'today':
            self.get_today_weather()
        elif date == 'tomorrow':
            self.get_tomorrow_weather_v1()
        else:
            raise RuntimeError('Error:unkown date')
        
    def get_today_weather(self):

        return self.get_weatehr_by_css(self.today_css_selectors)


    @property
    def tomorrow_weather_js_hash(self):
        format = 'return $("%s").first().text().trim()'
        return {
                'temp':format %(self.tomorrow_css_selectors['temp']),
                'weather':format %(self.tomorrow_css_selectors['weather']),
                'wind':format %(self.tomorrow_css_selectors['wind'])               
                }
        
    @property
    def  get_weather_by_css(self,css_hash):
        temp = self.dr.find_element_by_css_selector(css_hash['temp']).text 
        weather = self.dr.find_element_by_css_selector(css_hash['weather']).text        
        wind = self.dr.find_element_by_css_selector(css_hash['wind']).text 
        return {
                'temp':             temp,
                'weather':        weather,
                'wind':             wind               
                }
    
    def get_tomorrow_weather_v1(self):
        return {
                'temp':self.dr.execute_script(self.tomorrow_weather_js_hash['temp']),
                'weather':self.dr.execute_script(self.tomorrow_weather_js_hash['weather']),
                'wind':self.dr.execute_script(self.tomorrow_weather_js_hash['wind'])
                }
        
    def get_tomorrow_weather_v2(self):
        return self.get_weather_by_css(self.tomorrow_css_selectors)
    
    def quit(self):
        self.quit()











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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值