您的位置:首页 > 编程语言 > Python开发

Python爬虫简单的demo

2015-12-09 22:17 741 查看
利用python写了一个简单的爬虫程序:通知我《死神》漫画更新。

利用的是腾讯漫画http://ac.qq.com/Comic/comicInfo/id/501661,获得页面数据,利用正则表达式提取信息,判断是否更新,如果更新了就发送qq邮件通知我。程序运行在服务器上,每天早8点和晚8点个运行一次。

程序涉及了python的文件的读写,正则表达式,邮件发送。

如果你也想接收通知,留言邮箱即可 (^ - ^)

# -*- coding: utf-8 -*_
__author__ = 'wyz'

import urllib2
import re
import smtplib
import time
from email.mime.text import MIMEText

def sendmailTome(urls, title):
mail_to_list = ["962193430@qq.com"] #这里是接受的列表

mail_host = "smtp.qq.com"
mail_user = "962193430@qq.com" #这里是你的qq邮箱
mail_pass = "password" # 这里是密码,不是qq的密码,你需要开启smtp服务,他会给你一个16位的密码,就是那个密码

content = "您关注的死神更新了!!!!\n" + title + "\n地址:" + urls + "\n目录地址:http://ac.qq.com/Comic/comicInfo/id/501661"

msg = MIMEText(content)
msg['Subject'] = "死神更新啦"
msg["From"] = mail_user
msg["TO"] = ";".join(mail_to_list)

try:
s = smtplib.SMTP()
s.connect(mail_host)
s.login(mail_user, mail_pass)
s.sendmail(mail_user, mail_to_list, msg.as_string())
s.close()
return True
except Exception, e:
log.write(str(e) + '\n')
log.write(e)
log.write('\n')
return False

# 打开日志文件,记录时间
log = open('log.log', 'a+')
log.write("###############################################\n")
log.write(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) + "\n")

# 打开配置文件,读取集数和url
config_read = open("config.txt")
news = int(config_read.readline())
url = config_read.readline()
config_read.close()

# 进行内容读取
request = urllib2.Request(url)
response = urllib2.urlopen(request)
mypage = response.read()

# 正则匹配
getitems = re.findall(r'<a.*?title="死神/境·界:第' + str(news) + '话.*?" href="(.*?)">(.*?)</a>', mypage, re.S)

# 判断是否匹配到相应的内容,把相应的内容写到日志文件里
if len(getitems) > 0:
log.write("find" + str(news) + ', and send email.\n')

# 匹配成功,发送邮件
if sendmailTome("http://ac.qq.com" + getitems[0][0], getitems[0][1]):
log.write("send success.\n")

# 更新配置文件,方便下次读取
news += 1
config_write = open('config.txt', 'w')
config_write.write(str(news) + '\n')
config_write.write(str(url) + '\n')
config_write.close()

else:
log.write("send fail!!!!!!!!!!!!!!!!!!!!!!\n")

else:
log.write("not found " + str(news) + ". next find it agein.\n")

log.write('\n')
log.close()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息