python 爬取天氣並傳送郵箱

2021-09-07 06:36:48 字數 2392 閱讀 7509

以中國天氣網為例(www.weather.com.cn)

主要的實現步驟有:

一、對中國天氣網進行爬取

二、通過郵箱傳送提醒

完成**:

import requests

from bs4 import beautifulsoup

import smtplib

from email.mime.text import mimetext

from email.header import header

#爬取資料

#獲得網頁

def get_html(url):

res = requests.get(url)

res.encoding = 'utf-8'

return res.text

#解析網頁

def parser_html(html):

soup = beautifulsoup(html,'html.parser')

#今天天氣情況

today = soup.find_all(class_ = 'sky skyid lv3 on')

for todaydata in today:

wea = todaydata.find(class_ = 'wea').text

tem = todaydata.find(class_ = 'tem').text

todaycontent = "天氣:"+ wea + "溫度:" +tem

todaycontent = todaycontent.replace("\n","")

return todaycontent

#傳送資料

def sendemail(content):

# 第三方 smtp 服務

mail_host = "smtp.qq.com" # 設定伺服器

mail_user = "***x" # 使用者名稱

mail_pass = "******" # 口令

sender = '******x'

receivers = ['******x'] # 接收郵件,可設定為你的qq郵箱或者其他郵箱

message = mimetext(content, 'plain', 'utf-8')

message['from'] = header("******", 'utf-8')

message['to'] = header("******x", 'utf-8')

subject = 'python今日天氣'

message['subject'] = header(subject, 'utf-8')

try:

smtpobj = smtplib.smtp()

smtpobj.connect(mail_host, 25) # 25 為 smtp 埠號

smtpobj.login(mail_user, mail_pass)

smtpobj.sendmail(sender, receivers, message.as_string())

print("郵件傳送成功")

except smtplib.smtpexception:

print("error: 無法傳送郵件")

def main():

url = ''

html = get_html(url)

content = parser_html(html)

sendemail(content)

if __name__ == '__main__':

main()

拓展:

1.擴大到多日天氣情況

在解析網頁的時候,訓練使用bs4和re的綜合訓練

def parser_html(html):

soup = beautifulsoup(html,'html.parser')

today = soup.find_all(class_ = 'sky skyid lv3 ')

for todaydata in today:

wea = todaydata.find(class_ = 'wea').text

tem = todaydata.find(class_ = 'tem').text

todaycontent = "天氣:"+ wea + "溫度:" +tem

todaycontent = todaycontent.replace("\n","")

return todaycontent

2.實時任務

win10環境下python指令碼定時執行

Python 爬取中國天氣網天氣並通過郵箱定時傳送

獲取天氣資訊指令碼如下,usr bin python3 coding utf 8 import re import requests from bs4 import beautifulsoup import io import sys r requests.get timeout 30 r.rais...

python 爬取天氣

準備工作做好了,接下來就是 了 用py爬天氣資訊,需要使用兩個模組,分別是urllib2 獲取資料 和json 解析資料 coding utf 8 import urllib2 import json from city import city cityname raw input 你想查哪個城市的...

爬取天氣資訊並郵件傳送

直接上 usr bin env python coding utf 8 from urllib.request import urlopen from pyquery import pyquery as pq import smtplib from email.mime.text import mi...