要达到的目的:
从特定网页中抓取信息,排版后发送到邮箱中
关键点:
下载网页,从网页里抓取出需要的信息
HTML排版
发送到指定邮箱
实现:
1.python下载网页
直接用库函数就可以实现
from urllib import urlretrieve
from urllib import urlopen
doc = urlopen("http://roll.tech.sina.com.cn/tele/2012-05-01.shtml").read()
以获取新浪网5.1电信滚动新闻为例
doc就是整个网页的内容
2.用正则表达式提取新闻标题和url
def extract_url(info): #reg get url&titlerege = "<li><a href=\"(.*)\" target=_blank>"url = re.findall(rege,info)return urldef extract_title(info): pat = "\" target=_blank>(.*)</a><span class="title = re.findall(pat,info)return title
就可以得到新闻的URL和标题,以列表形式返回
3.排版
整理获得的信息,把信息排版成适合网页浏览的形式
我是把这些信息放到一个表格里
mail_context = "" mail_context += "<table width=\"700\" border=\"1\" align=\"left\" face=\"宋体\">" for i in range(0,n):mail_context += "<tr><td><font size=\"2\">"mail_context += "<span class="line1"><a href=\""mail_context += url[i]mail_context += "\" target=_blank>"mail_context += title[i]mail_context += "</a></span>"mail_context += "</font></td>" mail_context += "</table>"
4.获取excel中的邮件列表
def get_email_list():path = os.getcwd()wb = open_workbook(path+"\\email_list.xls")sheet=wb.sheet_by_name("email")first_column = sheet.col_values(0) return first_column
5.发送邮件
用自带的模块来发送,先登录到一个邮箱的服务器上,然后通过该邮箱向目的邮箱发送邮件
import smtplib from email.mime.text import MIMEText from email.MIMEMultipart import MIMEMultipart from email.Header import Headerdef sendsimplemail (text,dest):msg = MIMEText(text,'html','gb2312')#html formatmsg['Subject'] = Header('title', 'gb2312')msg['From'] = 'sourcedest'msg['To'] = str(dest)try:#login mail serversmtp = smtplib.SMTP()smtp.connect(r'smtp.*******')#mail serversmtp.login('username', 'password')#send mailsmtp.sendmail('sender', dest, msg.as_string())smtp.close()except Exception, e:print e
6.设置为开机自启动
以下是转的http://apps.hi.baidu.com/share/detail/22013974
下载python的win32支持。我使用的是:pywin32-202.win32-py2.3.exe安装好后就可以来写我们的服务了。
我们先来建立一个空的服务,建立test1.py这个文件,并写入如下代码:
# -*- coding: cp936 -*- import win32serviceutil import win32service import win32event class test1(win32serviceutil.ServiceFramework): _svc_name_ = "test_python" _svc_display_name_ = "test_python" def __init__(self, args): win32serviceutil.ServiceFramework.__init__(self, args) #把需要的操作都放在这里 self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) def SvcStop(self): # 先告诉SCM停止这个过程 self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) # 设置事件 win32event.SetEvent(self.hWaitStop) def SvcDoRun(self): # 等待服务被停止 win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE) if __name__=='__main__': win32serviceutil.HandleCommandLine(test1)
这里注意,如果你需要更改文件名,比如将win32serviceutil.HandleCommandLine(test1)中的test1更改为你的文件名,同时class也需要和你的文件名一致,否则会出现服务不能启动的问题。
在命令窗口执行,test1.py可以看到帮助提示
C:\>test1.py
Usage: 'test1.py [options] install|update|remove|start [...]|stop|restart [...]|
debug [...]'
Options for 'install' and 'update' commands only:
--username domain\username : The Username the service is to run under
--password password : The password for the username
--startup [manual|auto|disabled] : How the service starts, default = manual
--interactive : Allow the service to interact with the desktop. (for my auto_desktop.py, this option is needed)
C:\>
安装我们的服务
[code:1:05b7353f1c]C:\>test1.py install
Installing service test_python to Python class C:\test1.test1
Service installed
C:\>
我们就可以用命令或者在控制面板-》管理工具-》服务中管理我们的服务了。在服务里面可以看到test_python这个服务。
这样每次开机之后都可以收到一封邮件了