6754321 发表于 2016-12-23 09:08:24

用python+selenium从百度获取本地明日的天气信息并根据温度...

用python+selenium从百度获取本地明日的天气信息并根据温度情况邮件提醒
从百度天气获取当地明天的天气情况,如果明天下雨,请发送邮件通知全体同事带伞,
如果明天气温低于10度,请邮件提醒同事注意保暖,如果气温高于30度则提醒同事注意高温。
假设存在发送邮件的方法self.send_email(email_content)
代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#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').text #首先获取明日天气
      print('明日天气为%s' %weather)
      temperature = self.dr.find_elements_by_css_selector('.op_weather4_twoicon_temp').text #其次获取明日温度
      the_highest_temperature = int(temperature.split(' ~ ')) #从温度中获取明日最高温度并转为整型
      print('明日最高温度%s℃' %the_highest_temperature)
      the_lowest_temperature = temperature.split(' ~ ') #从温度中获取明日最低温度
      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()





网页如下:

结果如下:




页: [1]
查看完整版本: 用python+selenium从百度获取本地明日的天气信息并根据温度...