用Python加itchat寫一個(gè)爬蟲腳本每天定時(shí)給女朋友發(fā)微信暖心話

功能

定時(shí)給女朋友發(fā)送每日天氣、提醒、每日一句。

數(shù)據(jù)來源

每日一句和上面的大佬一樣也是來自O(shè)NE·一個(gè)

天氣信息來自SOJSON

實(shí)現(xiàn)效果

image
image

代碼說明

目錄結(jié)構(gòu)

image

city_dict.py :城市對(duì)應(yīng)編碼字典

config.yaml :設(shè)置定時(shí)時(shí)間,女友微信名稱等參數(shù)

GFWeather.py:核心代碼

requirements.txt:需要安裝的庫

run.py:項(xiàng)目運(yùn)行類

核心代碼

GFWeather.py

class gfweather:
 headers = {
 "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36",
 }
 # 女朋友的用戶id
 bf_wechat_name_uuid = ''
 def __init__(self):
 self.city_code, self.start_datetime, self.bf_wechat_name, self.alarm_hour, self.alarm_minute = self.get_init_data()
 def get_init_data(self):
 '''
 初始化基礎(chǔ)數(shù)據(jù)
 :return:
 '''
 with open('config.yaml', 'r', encoding='utf-8') as f:
 config = yaml.load(f)
 city_name = config.get('city_name').strip()
 start_date = config.get('start_date').strip()
 wechat_name = config.get('wechat_name').strip()
 alarm_timed = config.get('alarm_timed').strip()
 init_msg = f"每天定時(shí)發(fā)送時(shí)間:{alarm_timed}\n女友所在城市名稱:{city_name}\n女朋友的微信昵稱:{wechat_name}\n在一起的第一天日期:{start_date}"
 print(u"*" * 50)
 print(init_msg)
 # 根據(jù)城市名稱獲取城市編號(hào),用于查詢天氣。查看支持的城市為:http://cdn.sojson.com/_city.json
 city_code = city_dict.city_dict.get(city_name)
 if not city_code:
 print('您輸出城市無法收取到天氣信息')
 start_datetime = datetime.strptime(start_date, "%Y-%m-%d")
 hour, minute = [int(x) for x in alarm_timed.split(':')]
 # print(hour, minute)
 return city_code, start_datetime, wechat_name, hour, minute
 def is_online(self, auto_login=False):
 '''
 判斷是否還在線,
 :param auto_login:True,如果掉線了則自動(dòng)登錄。
 :return: True ,還在線,F(xiàn)alse 不在線了
 '''
 def online():
 '''
 通過獲取好友信息,判斷用戶是否還在線
 :return: True ,還在線,F(xiàn)alse 不在線了
 '''
 try:
 if itchat.search_friends():
 return True
 except:
 return False
 return True
 if online():
 return True
 # 僅僅判斷是否在線
 if not auto_login:
 return online()
 # 登陸,嘗試 5 次
 for _ in range(5):
 # 命令行顯示登錄二維碼
 # itchat.auto_login(enableCmdQR=True)
 itchat.auto_login()
 if online():
 print('登錄成功')
 return True
 else:
 return False
 def run(self):
 # 自動(dòng)登錄
 if not self.is_online(auto_login=True):
 return
 # 定時(shí)任務(wù)
 scheduler = BlockingScheduler()
 # 每天9:30左右給女朋友發(fā)送每日一句
 scheduler.add_job(self.start_today_info, 'cron', hour=self.alarm_hour, minute=self.alarm_minute)
 scheduler.start()
 def start_today_info(self):
 print("*" * 50)
 print('獲取相關(guān)信息...')
 dictum_msg = self.get_dictum_info()
 today_msg = self.get_weather_info(dictum_msg)
 print(f'要發(fā)送的內(nèi)容:\n{today_msg}')
 if self.is_online(auto_login=True):
 # 獲取好友username
 if not self.bf_wechat_name_uuid:
 friends = itchat.search_friends(name=self.bf_wechat_name)
 if not friends:
 print('昵稱錯(cuò)誤')
 return
 self.bf_wechat_name_uuid = friends[0].get('UserName')
 itchat.send(today_msg, toUserName=self.bf_wechat_name_uuid)
 print('發(fā)送成功..\n')
 def get_dictum_info(self):
 '''
 獲取格言信息(從『一個(gè)。one』獲取信息 http://wufazhuce.com/)
 :return: str 一句格言或者短語
 '''
 print('獲取格言信息..')
 user_url = 'http://wufazhuce.com/'
 resp = requests.get(user_url, headers=self.headers)
 soup_texts = BeautifulSoup(resp.text, 'lxml')
 # 『one -個(gè)』 中的每日一句
 every_msg = soup_texts.find_all('div', class_='fp-one-cita')[0].find('a').text
 return every_msg
 def get_weather_info(self, dictum_msg=''):
 '''
 獲取天氣信息。網(wǎng)址:https://www.sojson.com/blog/305.html
 :param dictum_msg: 發(fā)送給朋友的信息
 :return:
 '''
 print('獲取天氣信息..')
 weather_url = f'http://t.weather.sojson.com/api/weather/city/{self.city_code}'
 resp = requests.get(url=weather_url)
 if resp.status_code == 200 and resp.json().get('status') == 200:
 weatherJson = resp.json()
 # 今日天氣
 today_weather = weatherJson.get('data').get('forecast')[1]
 locale.setlocale(locale.LC_CTYPE, 'chinese')
 today_time = datetime.now().strftime('"%Y年%m月%d日 %H:%M:%S"')
 # 今日天氣注意事項(xiàng)
 notice = today_weather.get('notice')
 # 溫度
 high = today_weather.get('high')
 high_c = high[high.find(' ') + 1:]
 low = today_weather.get('low')
 low_c = low[low.find(' ') + 1:]
 temperature = f"溫度 : {low_c}/{high_c}"
 # 風(fēng)
 fx = today_weather.get('fx')
 fl = today_weather.get('fl')
 wind = f"{fx} : {fl}"
 # 空氣指數(shù)
 aqi = today_weather.get('aqi')
 aqi = f"空氣 : {aqi}"
 day_delta = (datetime.now() - self.start_datetime).days
 delta_msg = f'寶貝這是我們?cè)谝黄鸬牡?{day_delta} 天'
 today_msg = f'{today_time}\n{delta_msg}。\n{notice}\n{temperature}\n{wind}\n{aqi}\n{dictum_msg}\n來自最愛你的我。'
 return today_msg

項(xiàng)目運(yùn)行

安裝依賴

使用 pip install -r requirements.txt 安裝所有依賴

參數(shù)配置

config.yaml

#每天定時(shí)發(fā)送的時(shí)間點(diǎn),如:8:30
alarm_timed: '9:30'
# 女友所在城市名稱
city_name: '桂林'
# 你女朋友的微信名稱
wechat_name: '古典'
# 從那天開始勾搭的
start_date: '2017-11-11'

小編最近整理了一套Python學(xué)習(xí)教程,有需要的小伙伴,記得來小編的交流群:556370268,即可免費(fèi)領(lǐng)取一套Python學(xué)習(xí)教程哦

image
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 軟邇,一個(gè)九零后,談過三場(chǎng)戀愛。 初戀,初中,同班同學(xué),像往常的初戀一樣很甜很單純,180+的...
    軟邇閱讀 334評(píng)論 0 0
  • 我們?cè)?jīng)經(jīng)歷過許多一瞬間,有的讓我感動(dòng),有的讓我難忘,有的讓我高興,像天上閃爍的星星一樣,數(shù)也數(shù)不盡。我曾經(jīng)發(fā)生過...
    崔夢(mèng)欣閱讀 650評(píng)論 0 0
  • 因?yàn)榛ㄥX就是流水。 哪些地方花錢多呢?吃飯。吃飯,隨意可到30+,其實(shí)可以控制在15以內(nèi)的。就可以省很多錢。另外,...
    冬木暖陽閱讀 464評(píng)論 0 1
  • 一直以來都不是個(gè)喜歡寫作的人,一想到寫作,立即就會(huì)聯(lián)想到兩個(gè)詞——“絞盡腦汁”和“如臨大敵”。在端銀老師的組織下,...
    龍馬行天下閱讀 618評(píng)論 0 6
  • 最近弟弟在開始嘗試一個(gè)人睡覺,很是艱難,媽媽突然說起我當(dāng)年嘗試一個(gè)人睡的場(chǎng)景,深更半夜趁他們睡著,就披著被子偷偷下...
    稻草稻草和麥田閱讀 252評(píng)論 0 3

友情鏈接更多精彩內(nèi)容