python实现抓取网页上的内容并发送到邮箱
要達到的目的:
從特定網(wǎng)頁中抓取信息,排版后發(fā)送到郵箱中
?
關(guān)鍵點:
下載網(wǎng)頁,從網(wǎng)頁里抓取出需要的信息
HTML排版
發(fā)送到指定郵箱
?
實現(xiàn):
1.python下載網(wǎng)頁
直接用庫函數(shù)就可以實現(xiàn)
from urllib import urlretrieve
from urllib import urlopen
doc = urlopen("http://roll.tech.sina.com.cn/tele/2012-05-01.shtml").read()
以獲取新浪網(wǎng)5.1電信滾動新聞為例
doc就是整個網(wǎng)頁的內(nèi)容
?
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.排版
整理獲得的信息,把信息排版成適合網(wǎng)頁瀏覽的形式
我是把這些信息放到一個表格里
?
?
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.發(fā)送郵件
用自帶的模塊來發(fā)送,先登錄到一個郵箱的服務器上,然后通過該郵箱向目的郵箱發(fā)送郵件
?
?
6.設置為開機自啟動
以下是轉(zhuǎn)的http://apps.hi.baidu.com/share/detail/22013974
下載python的win32支持。我使用的是:pywin32-202.win32-py2.3.exe安裝好后就可以來寫我們的服務了。
我們先來建立一個空的服務,建立test1.py這個文件,并寫入如下代碼:
?
?
這里注意,如果你需要更改文件名,比如將win32serviceutil.HandleCommandLine(test1)中的test1更改為你的文件名,同時class也需要和你的文件名一致,否則會出現(xiàn)服務不能啟動的問題。
在命令窗口執(zhí)行,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這個服務。
這樣每次開機之后都可以收到一封郵件了
?
轉(zhuǎn)載于:https://www.cnblogs.com/w0w0/archive/2012/05/02/2478639.html
總結(jié)
以上是生活随笔為你收集整理的python实现抓取网页上的内容并发送到邮箱的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: redis杂谈
- 下一篇: UVa 10905 孩子们的游戏