从百度天气获取当地明天的天气情况,如果明天下雨,请发送邮件通知全体同事带伞,

如果明天气温低于10度,请邮件提醒同事注意保暖,如果气温高于30度则提醒同事注意高温。

假设存在发送邮件的方法self.send_email(email_content)

代码如下:

#coding=utf-8
from selenium import webdriver
import unittest
from time import sleep

class WeatherReport(unittest.TestCase):

    def setUp(self):
        self.dr = webdriver.Chrome()
        self.weather, self.the_highest_temperature, self.the_lowest_temperatrue = self.get_tomorrow_weather_and_temperature()
        self.content = self.email_content()

    def get_tomorrow_weather_and_temperature(self):
        self.baidu_search('成都天气')
        sleep(5)
        weather = self.dr.find_elements_by_css_selector('.op_weather4_twoicon_weath')[1].text #首先获取明日天气
        print('明日天气为%s' %weather)
        temperature = self.dr.find_elements_by_css_selector('.op_weather4_twoicon_temp')[1].text #其次获取明日温度
        the_highest_temperature = int(temperature.split(' ~ ')[0]) #从温度中获取明日最高温度并转为整型
        print('明日最高温度%s℃' %the_highest_temperature)
        the_lowest_temperature = temperature.split(' ~ ')[1] #从温度中获取明日最低温度
        print('明日最低温度%s' %the_lowest_temperature)
        return weather, the_highest_temperature, the_lowest_temperature

    def baidu_search(self, CityWeather):
        self.dr.get('http://www.baidu.com')
        self.dr.find_element_by_id('kw').send_keys(CityWeather)
        self.dr.find_element_by_id('su').click()

    def email_content(self):
        if '雨' in self.weather:
            content = '通知:明天有雨,请全体同事带伞!'
        else:
            if self.the_highest_temperature > 30:
                content = '提醒:明日气温高于30度,请全体同事注意高温'
            elif self.the_highest_temperature < 10:
                content = '提醒:明日气温低于10度,请全体同事注意保暖'
            else:
                content = ''
        return content

    def test_send_email(self):
        print('%s' %self.content)

    def tearDown(self):
        self.dr.quit()

if __name__ == '__main__':
    unittest.main()


网页如下:

spacer.gif

结果如下: