Python爬虫简单的demo

利用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()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值