Python3爬取墨迹天气页面,并发送邮箱提醒

import requests
from bs4 import BeautifulSoup
import smtplib
import lxml
from email.mime.text import MIMEText
'''
思路:获取所有省份的a标签
把所有a标签链接和名称用字典存储
让用户进行输入,来匹配,返回市县区
再次返回市县区的a标签,再让用户输入信息,匹配对应市县区的数据进行返回
最后拿到天气页面的信息
发送到指定邮箱
'''
url = 'https://tianqi.moji.com/weather/china'
req = requests.get(url)
html = req.text
bf = BeautifulSoup(html, "lxml")
div = bf.find_all("div", class_= "city clearfix")
bf2 = BeautifulSoup(str(div), 'lxml')
a_list = bf2.find_all('a')
dic = {}
#遍历所有a标签
for item in a_list:
    name = item.string
    url ="https://tianqi.moji.com" +  item.get("href")
    dic[name] = url
print("===================WY天气系统")
# sheng = input("请输入省份(eg:河南): ")
sheng = '山东'
while sheng not in dic:
    print("Input error(eg: 河南): ")
    sheng = input("请输入省份(eg:河南): ")
sheng_url = dic[sheng]
#对省份链接访问,解析获取所有a标签
req = requests.get(sheng_url)
html = req.text
bf = BeautifulSoup(html, 'lxml')
div = bf.find_all("div", class_ = "city_hot")
#获取a标签
bf = BeautifulSoup(str(div), 'lxml')
a_list = bf.find_all('a')
dic_xian = {}

for item in a_list:
    dic_xian[item.string] = item.get("href")
print(dic_xian)
xian = "烟台市"
while xian not in dic_xian:
    xain = input("Input error(eg: 信阳市,浉河区/光山县):")
    xian = input("请输入您选择%s设的市县区(信阳市,浉河区/光山县):" % sheng)
#获取meta 标签
req = requests.get(url = dic_xian[xian])
html = req.text
bf = BeautifulSoup(html, 'lxml')
meta_list = bf.find_all('meta')

meta = meta_list[2].get("content")
meta = meta.replace("墨迹天气", "您最亲爱的师傅")
meta = meta.replace("年老体弱者可以穿着呢大衣增加保暖系数。", "没有穿紫色秋裤的你,一点也不酷。")
# to = input("请输入qq:")
server = "smtp.qq.com"  #定义服务
user = "###############@qq.com"  #账号
pwd = 'u############'          # 密码或者授权码
content = meta    #邮箱内容设定
message = MIMEText(content)
message["subject"] = "来自远方的关怀"   #设置主题
message["From"] = user     #发件人
to = "############[email protected]"  #收件人
smtp_email = smtplib.SMTP(server, 25) #定义邮箱服务器
smtp_email.login(user = user, password = pwd)  #登陆邮箱
smtp_email.sendmail(from_addr = user, to_addrs= to , msg= message.as_string()) #发送
smtp_email.quit()  #断开退出邮箱
发布了84 篇原创文章 · 获赞 10 · 访问量 8571

猜你喜欢

转载自blog.csdn.net/AK47red/article/details/103777400