144
社区成员




学号 2022-2023-2 《Python程序设计》实验四报告
课程:《Python程序设计》
班级:2234
姓名:范欣怡
学号:20223427
实验教师:王志强
实验日期:2022年5月15日
必修/选修: 公选课
1.实验内容
此处填写实验的具体内容;
设计爬虫程序,获取网页上的天气信息,并通过邮件的方式发送给自己。
2. 实验过程及结果
(1)实验过程
A.导入与爬虫有关的库
B.获取所爬取网页的url,并进行UA伪装
C.建立获取天气情况的正则表达式
D.建立字典,处理数据
E.将字典中的数据取出,进行处理
F.编写邮件发送代码
G.调试运行
(2)实验源代码
import requests
import re
import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr
from Tools.scripts.which import msg
url = 'http://www.weather.com.cn/weather/101010900.shtml'
header = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)'
'Chrome/92.0.4515.131 Safari/537.36 SLBrowser/8.0.1.1171 SLBChan/32'}
response = requests.get(url=url,headers=header)
response.encoding= 'utf-8'
weather_text = response.text
tem = '<li class=".*?">.*?<h1>(.*?)</h1>'
tem2 = '</big>.*?<p title="(.*?)" class="wea"'
tem3 = '<p class="tem">.*?<i>(.*?)</i>'
tem4 = '<p class="tem">.*?<span>(.*?)</span>'
date_list = re.findall(tem,weather_text, re.S)
condition_list = re.findall(tem2, weather_text, re.S)
min_tempture_list = re.findall(tem3, weather_text, re.S)
max_tempture_list = re.findall(tem4, weather_text, re.S)
weather_condition = {}
weather_tempture_min = {}
weather_tempture_max = {}
if len(max_tempture_list) == 6:
weather_tempture_max[date_list[0]] = '无'
for each in range(0, 3):
weather_condition[date_list[each]] = condition_list[each]
weather_tempture_min[date_list[each]] = min_tempture_list[each]
for i in range(1, 3):
weather_tempture_max[date_list[i]] = max_tempture_list[i]
else:
for each in range(0, 3):
weather_condition[date_list[each]] = condition_list[each]
weather_tempture_min[date_list[each]] = min_tempture_list[each]
weather_tempture_max[date_list[each]] = max_tempture_list[each]
text1 = []
for n in range(0, 3):
text1.append('日期:' + date_list[n] + '\n天气状况:' + weather_condition[date_list[n]] + '\n最低温--最高温:' +
weather_tempture_min[date_list[n]] + '-' + weather_tempture_max[date_list[n]])
text2 = text1[0] + '\n' + text1[1] + '\n ' + text1[2]
print(text2)
fromfxyyy = '2463157225@qq.com'
password = 'pcjhiwlokpcdeaff'
tofxyyy = '2463157225@qq.com'
def mail():
mail_text=text1[0]
ret = True
try:
msg = MIMEText(mail_text)
msg['From'] = formataddr(["From@一只小游鱼", fromfxyyy])
msg['To'] = formataddr(["一只小游鱼", tofxyyy])
msg['Subject'] = "今日天气"
server = smtplib.SMTP_SSL("smtp.qq.com")
server.login(fromfxyyy, password)
server.sendmail(fromfxyyy, [tofxyyy], msg.as_string())
server.quit()
except Exception:
ret = False
return ret
ret = mail()
if ret:
print("邮件发送成功")
else:
print("邮件发送失败")
(3)实验截图