從百度天氣獲取當地明天的天氣情況,如果明天下雨,請發送郵件通知全體同事帶傘,
如果明天氣溫低於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()
網頁如下:
結果如下: