时间:2021-07-01 10:21:17 帮助过:87人阅读
代码如下:
#!/usr/bin/env python
#coding:UTF-8
import urllib2
from sgmllib import SGMLParser
import smtplib
import time
#from email.mime.text import MIMEText
#from bs4 import BeautifulSoup
#import re
class UrlParser(SGMLParser):
urls = []
def do_a(self,attrs):
'''''parse tag a'''
for name,value in attrs:
if name=='href':
self.urls.append(value)
else:
continue
def do_link(self,attrs):
'''''parse tag link'''
for name,value in attrs:
if name=='href':
self.urls.append(value);
else:
continue
def checkUrl(checkurl, isDetail):
'''''检查checkurl对应的网页源码是否有非法url'''
parser = UrlParser()
page = urllib2.urlopen(checkurl)
content = page.read()
#content = unicode(content, "gb2312").encode("utf8")
parser.feed(content)
urls = parser.urls
dailyUrls = []
detailUrl = ""
for url in urls:
if 'daily' in url:
dailyUrls.append(url);
if not detailUrl and not isDetail and 'www.bc5u.com' in url:
detailUrl = url
page.close()
parser.close()
if isDetail:
return dailyUrls
else:
return dailyUrls,detailUrl
def sendMail():
'''''发送提醒邮件'''
pass
def log(content):
'''''记录执行日志'''
logFile = 'checkdailyurl.log'
f = open(logFile,'a')
f.write(str(time.strftime("%Y-%m-%d %X",time.localtime()))+content+'\n')
f.flush()
f.close()
def main():
'''''入口方法'''
#检查ju
url = "www.bc5u.com"
dailyUrls,detailUrl=checkUrl(url, False)
if dailyUrls:
#检查到daily链接,发送告警邮件
sendMail()
log('check: find daily url')
else:
#没检查到daily链接,不处理
log('check: not find daily url')
#检查judetail
dailyUrls=checkUrl(detailUrl, True)
if dailyUrls:
#检查到daily链接,发送告警邮件
log('check: find daily url')
sendMail()
else:
#没检查到daily链接,不处理
log('check: not find daily url')
if __name__ == '__main__':
main()