本人Python大菜鸟,今天用python写了一个脚本。主要功能是获取贴吧指定贴子评论中留下的邮箱,通过系统的crontab每一分钟自动检测新邮箱并向其发送邮件,检测机制是去查询数据库的记录,也就是不会向已经发送过的邮箱再次发送邮件(当然如果有人连续留下两次邮箱,脚本会不断给他发送邮件,直到有人留下了新邮箱地址,这个也算是脚本的bug吧,不过谁让你连续留两次呢)。

运行环境是python2.6,centos6.3 64位

主文件main.py脚本内容如下:

import mysql_class
import cookielib
from email.mime.text import MIMEText
from email.MIMEMultipart import MIMEMultipart
import sys,urllib2,string,re,time,smtplib,json
def sendsimplemail(content,List,subject):
    today = time.strftime('%m-%d')
    msg = MIMEText(content)
    msg['Subject'] = today + "\t" + subject
    msg['From'] = 'xxx@xxx.com'
    try:
        smtp = smtplib.SMTP()
        smtp.connect(r'127.0.0.1')
        smtp.login('tank', 'tank')
        smtp.sendmail('xxx@xxx.com', List, msg.as_string())
        smtp.close()
    except Exception, e:
        print e

db=mysql_class.mySqlConn()
resall=db.GetFetch("select * from config")
for res in resall:
    tieba_id=str(res[0])
    myUrl="http://tieba.baidu.com/p/"+tieba_id
    minIndex=int(res[1])
    lastmail=res[2]
    firstPattern=re.compile(r'(\?pn=\d+)$')
    myUrl=re.sub(firstPattern,'',myUrl)
    try:
        print(time.strftime('%Y-%m-%d-%H-%M-%S:',time.localtime(time.time())))
        '''count the totalpage'''
        cj = cookielib.CookieJar()
        opener=urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
        response=opener.open(myUrl)
        myPage=response.read()
        pagecount=re.compile(r'span class="red">(\d+)</span>')
        match = pagecount.search(myPage)
        if match:
            totalpage=match.group(1)
          maxIndex=int(totalpage)

        '''count the mail addr'''
        for i in range(minIndex,maxIndex+1):
            index=myUrl.rfind(r'?pn=')
            if index==-1:
                myUrl=myUrl+r'?pn='+str(i)
            else:
                myUrl=re.sub(firstPattern,r'?pn='+str(i),myUrl)
            print(myUrl)
        response=opener.open(myUrl)
            myPage=response.read()
            myPage=myPage.decode('GBK')
            myPage=myPage.replace(r'\r\n','')
        if i == minIndex:
            print 'go....'
            lastmail_content=re.compile(lastmail+r'(.*)')
            match = lastmail_content.search(myPage)
            if match:
                myPage=match.group(1)
            else:
            print 'not match'
            pattern=re.compile(r'([a-zA-Z0-9]+@[a-zA-Z0-9]+\.?[a-zA-Z0-9]+\.+[a-zA-Z0-9]+)')
            result=pattern.findall(myPage)
            if result is not None:
                #for email in result:
            #print email
            List = [email for email in result]
            print List
             file_object = open('/root/bin/tieba/mail_content.txt')
            content=file_object.read()
            file_object2 = open('/root/bin/tieba/mail_subject.txt')
             subject=file_object2.read()
            sendsimplemail(content,List,subject)

            else:
                print("not found")
        if i == maxIndex:
            lastmail=result[len(result)-1]
        sql="UPDATE config SET pn_begin="+str(maxIndex)+",last_mail='"+str(lastmail)+"' WHERE tieba_id="+str(tieba_id)
        db.Query(sql)
        db.Close()
        print('Suceed!!!')
    except Exception as e:
        print("something wrong or not new mailer")

其中用到了mysql_class,将python操作mysql写成一个类,放在同级目录下的mysql_class.py里(有一些方法没有用到),内容如下:

import MySQLdb
class  mySqlConn:
    """This class is connect to mysql"""
    def __init__(self, host="xxxxx", user="mail", password="mail123", db="mail"):
        """Construct function,
        connect to mysql,
        and set names utf8"""
        self.__mqUser__ = user
        self.__mqPass__ = password
        self.__mqHost__ = host
        self.__mqDb__ = db
        try:
            self.__conn__ = MySQLdb.Connect(user=self.__mqUser__, passwd=self.__mqPass__, host=self.__mqHost__, db=self.__mqDb__)
        except:
            print("Count not connect to MySQL server.")
            exit(0)
        self.__cursor__ = self.__conn__.cursor()
        try:
            self.__cursor__.execute("set names utf8")
        except:
            print("Excute `set names utf8` faild.")
            exit(0)
    def Query(self, sql):
        """ Execute a sql """
        try:
            self.__cursor__.execute(sql)
        except:
            print(sql)
            print("Sql excute faild!")
    def GetMqCursor(self):
        """Get Mysql Cursor"""
        return self.__cursor__
    def GetFetchOne(self,sql):
        """Get fetch row"""
        self.__cursor__.execute(sql)
        return self.__cursor__.fetchone()
    def GetFetch(self,sql):
        """Get fetch row"""
        self.__cursor__.execute(sql)
        return self.__cursor__.fetchall()
    def Close(self):
        """Close the mysql connect"""
    self.__conn__.commit()
        self.__cursor__.close()
    self.__conn__.close()

main.py还用到了发送邮件功能,邮件服务器是我自己搭建的postfix+saslauthed+cyrsu-imap,没时间自己弄邮件服务器的可以用第三方的发信功能(个人认为,没用Python测试过)。

数据库名mail,表名:config,表结构如下(主要是用来存放贴吧id,上次记录的帖子的最大页数,还有上次记录的最后一个邮箱):
| Field     | Type         | Null | Key | Default | Extra |
+-----------+--------------+------+-----+---------+-------+
| tieba_id  | varchar(100) | NO   | PRI | 1       |       |
| pn_begin  | int(11)      | NO   |     | 1       |       |
| last_mail | varchar(100) | NO   |     |         |       |
+-----------+--------------+------+-----+---------+-------+

另外发信的标题和内容我是放在文本里的,这样方便更新(也是因为我发现直接写在程序里会乱码,知道怎么解决的请留言告诉我哦,感激不尽)。

发信标题文本:mail_subject.txt,内容省略啦。

发信内容文本:mail_content.txt,内容省略啦。

脚本经过本人测试可行,qq邮箱可以发送,编码也没有问题,但是163邮箱貌似会乱码,有知道的朋友请指教。

-------------------------------------------------------黄金分割线-------------------------------------------------------------------

嘿嘿,其实我是向贴吧里的人推荐给力的VPN的,借此机会也向你们推荐一下哈,NydusVPN,目前俺用过的最给力的,有需要的朋友试试看:官网地址

Python实时获取贴吧邮箱名单并向其发送邮件的更多相关文章

  1. 使用Python实时获取cmd的输出

    最近发现一个问题,一个小伙儿写的console程序不够健壮,监听SOCKET的时候容易崩,造成程序的整体奔溃,无奈他没有找到问题的解决办法,一直解决不了,可是这又是一个监控程序,还是比较要紧的,又必须 ...

  2. 用Python实时获取Steam特惠游戏数据,我看看谁的钱包还有钱

    前言 大家好鸭, 我是小熊猫 Steam大家应该不陌生吧?不知道的话就让我们来了解一下吧~(一下简称"S") S是由美国电子游戏商Valve于2003年9月12日推出的数字发行平台 ...

  3. 这个帖子要收藏,以后用得着--python 实时获取子进程输出

    在论坛上找到方法了,http://bbs.csdn.net/topics/340234292 http://blog.csdn.net/junshao90/article/details/821575 ...

  4. Python实时语音识别控制

    代码地址如下:http://www.demodashi.com/demo/12946.html Python实时语音识别控制 概述 本文中的语音识别功能采用 百度语音识别库 ,首先利用 PyAudio ...

  5. 使用python发邮件(qq邮箱)

    今天打算用QQ邮箱作为示例使用的邮箱,其他邮箱基本操作一样. 第一步:首先获取QQ邮箱授权码 1.进入QQ邮箱首页,点击设置,如图, 2.然后点击账户 3.拉到这个地方,开启POP3/SMTP服务服务 ...

  6. subprocess.Popen stdout重定向内容实时获取

    python 打开一个新进程执行系统命令, test 执行完才能获取返回, test1 实时获取返回结果 import subprocess def test(cmd): p = subprocess ...

  7. PyQt学习随笔:Model/View中视图数据项编辑变动实时获取变动数据的方法

    对于Model/View中视图的数据编辑后怎么能实时获取编辑的数据变动位置和变动情况查阅了一些资料,终于基本弄明白必须重写Model的setData方法才能截获.setData方法是视图中各种角色数据 ...

  8. 【NLP】Python NLTK获取文本语料和词汇资源

    Python NLTK 获取文本语料和词汇资源 作者:白宁超 2016年11月7日13:15:24 摘要:NLTK是由宾夕法尼亚大学计算机和信息科学使用python语言实现的一种自然语言工具包,其收集 ...

  9. 使用python+xpath 获取https://pypi.python.org/pypi/lxml/2.3/的下载链接

    使用python+xpath 获取https://pypi.python.org/pypi/lxml/2.3/的下载链接: 使用requests获取html后,分析html中的标签发现所需要的链接在& ...

随机推荐

  1. 别人整理的DP大全(转)

    动态规划 动态规划 容易: , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ...

  2. 阐述ArrayList、Vector、LinkedList的存储性能和特性?(转)

    ArrayList 和Vector他们底层的实现都是一样的,都是使用数组方式存储数据,此数组元素数大于实际存储的数据以便增加和插入元素,它们都允许直接按序号索引元素,但是插入元素要涉及数组元素移动等内 ...

  3. firebug常用工具

    1.console.group("第一组"); console.log(1); console.groupend(); 2.console.dir(对象);//输出对象的所有信息 ...

  4. VMware/Microsoft官网查询参加的培训及认证信息

    如果你参加了VMWare的培训,会要求你拿一个已经注册的邮箱加上一个密码在VMware的系统里面登记,这样你就能在VMWARE官网查到注册,并据此你才能申请VMWare的考试认证. 例如下图,路径为 ...

  5. NOIP模拟赛-护花

    [题目描述] 约翰留下他的N(N<=100000)只奶牛上山采木.他离开的时候,她们像往常一样悠闲地在草场里吃草.可是,当他回来的时候,他看到了一幕惨剧:牛们正躲在他的花园里,啃食着他心爱的美丽 ...

  6. android嵌套unity3d

    最近因为跟小伙伴在制作一个App参加比赛,由于有unity的开发经验,突发奇想的想要在Android应用中内嵌unity提供模型展示的功能. 为此,我们查阅了不少资料.大多发现的是unity中内嵌An ...

  7. PCI Express(六) - Simple transactions

    原文地址:http://www.fpga4fun.com/PCI-Express6.html Let's try to control LEDs from the PCI Express bus. X ...

  8. Mysql的一些常用方法

    公司近期为新来同事做了一次培训,我也偷偷溜进去观摩了一下,内容虽然很基础,但是还是挺有用的.这里做了一下资料汇总: 2种存储引擎 InnoDB:支持事务处理.外键.行级锁,游戏业务库使用 MyISAM ...

  9. MFC创建文件和文件夹

    1.使用PathIsDirectory判断文件夹是否存在需要引用下面头文件: #include "shlwapi.h"#pragma comment(lib,"shlwa ...

  10. js数组中去除重复对象及去除空对象的方法

    (function(){//去除数组中重复对象 var unique = {}; arr.forEach(function(a){ unique[ JSON.stringify(a) ] = 1 }) ...