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
| from bs4 import BeautifulSoup import requests import Email #Email是自己写的邮件发送功能 #目标网址 url = 'http://www.weather.com.cn/weather/101230601.shtml' rs = requests.get(url) rs.encoding='utf-8' # print(rs.text) soup = BeautifulSoup(rs.text,'html.parser')
#分析网页会发现日期是h1标签之中 h1 = soup.find_all('h1') # 用css选择器来获取天气状况,由于用标签比css选择器复杂的多所以不选用 where = soup.select('p[class="wea"]') #选取温度 temp = soup.select('p[class ="tem"]') T = [] #对取到的温度进行处理 for t in temp: # print(t.text.replace('\n','')) T.append(t.text.replace('\n','')) # 一下是邮件内容的构建并且发送 Text = "{}这时候的温度是{},天气状况是:{};\n".format(h1[0].text,T[0] ,where[0].text) Text+="{}的时候,天气状况是{},气温是{};\n".format(h1[1].text,where[1].text,T[1]) Text+="{}的时候,天气状况是{},气温是{};\n".format(h1[2].text,where[2].text,T[2]) Text+="{}的时候,天气状况是{},气温是{};\n".format(h1[3].text,where[3].text,T[3]) Text+="{}的时候,天气状况是{},气温是{};\n".format(h1[4].text,where[4].text,T[4]) Text+="{}的时候,天气状况是{},气温是{};\n".format(h1[5].text,where[5].text,T[5]) Text+="{}的时候,天气状况是{},气温是{};\n".format(h1[6].text,where[6].text,T[6]) # print(Text) From = 'sd@qq.com' Title = '天气预报' To = 'zhhhy' From_addr = 'sd@qq.com' from_pwd = 'ssdasd' To_addr = 'ds@qq.com'
try: msg = Email.build_Text(text=Text, From=From, title=Title, To=To) Email.send_Email(text=Text, from_addr=From_addr, from_pwd=from_pwd, to_addr=To_addr, msg=msg) print("邮件发送成功!") except Exception as e: print("邮件发送失败:", e)
|