python-給微信好友自動發送天氣預報和每日一句


周末在宿舍學習python,女朋友那突然下了傾盆大雨,在圖書館門口跟我抱怨好久。最近又在學習python,就想給女朋友寫個小程序,每天早上將每天的天氣預報通過微信發個她。

在本程序中,用到了幾個重要的模塊,操作微信的wxpy模塊,直接打開網頁內容的urlopen,以及搜索html文件的Beautifulsoup在文件開始加上# -*- coding:utf-8 -*-是因為python文件中是不支持中文的,通過開始這個代碼可以讓文件編碼類型改為UTF-8以支持中文。

# -*- coding:utf-8 -*-
import datetime
import time
import wxpy
from urllib.request import urlopen
from bs4 import BeautifulSoup

 通過urlopen模塊從想要獲取信息的網站獲取信息,接着用BeautifulSoup模塊解析HTML。再跟據相應的方法取得想要的tag。

 1 #打開中國天氣網的紹興7天天氣
 2 resp=urlopen('http://www.weather.com.cn/weather/101210501.shtml')
 3 soup=BeautifulSoup(resp,'html.parser')
 4 
 5 #weather作為明天天氣變量
 6 TomorrowWeather=soup.find_all('p',class_="wea")[1].string
 7 TodayWeather=soup.find_all('p',class_="wea")[0].string
 8 
 9 #今天高低溫度
10 TodayTemperatureHigh=soup.find_all('p',class_="tem")[0].span.string
11 TodayTemperatureLow=soup.find_all('p',class_="tem")[0].i.string
12 
13 #明天高低溫度
14 TomorrowTemperatureHigh=soup.find_all('p',class_="tem")[1].span.string
15 TomorrowTemperatureLow=soup.find_all('p',class_="tem")[1].i.string

接着用類似的方法從“ONE”上獲取每日一句。

1 """獲取每日一句的內容"""
2 resp=urlopen('http://www.wufazhuce.com/')
3 soup=BeautifulSoup(resp,'html.parser')
4 
5 text=soup.find_all('a')[2].string

最后通過模塊datetime獲取時間,並設定好時間發送這些消息。

 1 '''get time now'''
 2 nowtime=datetime.datetime.now()
 4 '''send message at time'''
 5 if nowtime.hour==7 and nowtime.minute==0:
 6     print('send weather forecast')
 7     weather=get_weather()
 8     girlfriend=bot.search('Blueberry')[0]
 9     girlfriend.send(weather)
10     if TodayWeather.find('')!=-1 :
11         girlfriend.send('出門記得帶好傘哦~')
12     time.sleep(60)
13 if nowtime.hour==22 and nowtime.minute==0:
14     print('send news')
15     dailysentence=news.get_news()
16     girlfriend=bot.search('Blueberry')[0]
17     girlfriend.send(dailysentence)
18     girlfriend.send('--每日一句')
19     time.sleep(60)

以上就是全部的代碼了。這是我學習了python后第一次自己編寫的一個完整的代碼,很簡單。就當練練手,以后如果工作有自動化測試的需要,再嘗試寫點其他的。

學以致用。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM