关于Python动态网页爬取的实践记录


一、前言

最初了解到爬虫是在一个机缘巧合之下,当时觉得很神奇、挺有意思,然后就主动了解,从最开始的静态网页,到动态加载网页,从requests到selenium,再回到requests(尝试分析动态网页json)。本文用来记录我在学习过程中的一些心得体会。


本文主要记录我的第一个实际应用意义的爬虫的开发经历与其中的一些心得体会

二、开发背景

目前国内疫情没有完全平息,各大企事业单位、高校等仍然坚持实行每日健康打卡制度。本人目前为某大学本科生,同时作为一班之长,肩负着提醒班上同学打卡的义务(提醒班上每位同学做好每人健康打卡登记)。然而每天总是去催他们打卡,总是会招人厌烦,而每天健康打卡情况是通过网页进行公示的。于是我便想到使用Python爬虫爬取未打卡人员信息,然后通过程序去提醒这些人,说干就干。

三、需求分析

  • 1.爬虫爬取网页未打卡人员信息
  • 2.信息关联邮箱地址,通过邮件提醒(Python邮件模块)
  • 3.信息中包含手机号等信息,使用短信提醒(云短信模块¥¥
  • 4.作为班长,我需要知道每天同学的打卡情况(情况汇总)
  • 4.程序需要持续运行,每天固定时间开始提醒

四、开发经历

整个程序的开发大概经历了好几个阶段,我大概叙述一下。

1.requests直接获取网页数据

由于我是初次了解爬虫并独立开发,所以一开始不太了解动态网页机制,将网页当做静态网页直接处理,在网页还未加载完成时就直接获取了网站源码,因此不能获取到同学信息,只看到了正在加载的提示。于是我便想到如何让网页加载完全后再提取网页源码,此时便能在源码中找到人员信息。于是进入第二阶段。

2.selenium操作web浏览器模拟点击

通过搜索处理动态网页的工具,我找到了selenium,能够操作浏览器打开网页、在网页加载完成后进行操作、屏幕截图等。
我使用它成功取得了同学的信息,通过SMTP进行邮件的发送,提醒同学打卡。通过注册云短信平台,使用短信发送接口发送提醒短信。对结果进行截图,然后发送给我自己的邮箱,每天可以查看打卡情况,这是1.0版本。
同时,我使用PyQt5进行界面设计,能够良好显示运行日志等信息,然而,这个程序只能在Window10的系统上运行,并且运行过程中需要占用大量的内存和CPU算力(需要操作浏览器),导致我在云端部署程序时,需要性能更优秀的机器,导致需要花费更多的¥。我决心改进程序,因此2.0版本诞生了。。。

3.requests请求后台数据

通过分析网页的请求数据,我发现在网页的后台数据是通过请求特定的网页产生的
后台数据

然而,我直接请求这个网页却显示未登录,而非之前看到的数据
显示未登录

接着发现了每次请求的cookie是动态变化的,我的处理方法是,每次先请求一次主网页链接,从当前网页中获取cookie数据,添加到数据请求链接的请求头中

url1 = '主请求地址'
url2 = "数据请求地址"
session = requests.session()
# 首次进入,获取随机Cookie
r = session.get(url1)
cookie = r.cookies.values()[0]
header = {
    'Cookie': 'JSESSIONID=' + cookie
}
response = session.post(url=url2, headers=header)

然后得到了下图这样的情况
没有数据

并没能获得数据,得到了空的回应
原来是正常的post请求携带了json数据,修改代码,在请求中添加json数据

# jsons = {"bmid": "'4007013'", "cxsj": date, "cxbmjb": "3", "cxlx": "0"}

# 修改后的代码
url1 = '主请求地址'
url2 = "数据请求地址"
# 请求携带json数据
jsons = {"bmid": "'4007013'", "cxsj": "xxxx-xx-xx", "cxbmjb": "3", "cxlx": "0"}

session = requests.session()
# 首次进入,获取随机Cookie
r = session.get(url1)
cookie = r.cookies.values()[0]
header = {
    'Cookie': 'JSESSIONID=' + cookie
}

response = session.post(url=url2, json=jsons, headers=header)
# 未打卡人员信息
data = json.loads(response.text)['data']
print(data)

至此,就能完整获取请求数据了yes!
在这里插入图片描述

五、遇到的问题

在程序设计过程中遇到的问题,其实主要出在Windows程序移植到Linux的过程中。程序在Windows系统下编写完成,上传到阿里云轻量级服务器中运行,遇到的问题大概有以下几点:

  • 1.Windows程序移植到Linux后,出现了编码异常的问题,导致中文字符不能正常显示读取等,为Unicode编码形式。
  • 2.阿里云服务器的25端口被禁用,无法使用该端口发送邮件
  • 3.邮件发送容易失败,发送邮件响应慢

具体问题下一篇博文分析。。。。

六、代码分享

Auto_seek.py(程序主体)

# encoding: utf-8
import datetime
import json
import pathlib
import smtplib
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from time import sleep
import requests

ADMIN_EMAIL = ''  # 设置管理员邮箱账号,接收汇总情况
ADMIN_TEL = ''  # 管理员手机号,接受短信提醒
LOG_FILE = 'auto_seek.log'  # 运行日志文件


def send_mail(recv, title, content, file=None):
    """
    发送邮件函数,默认使用163smtp
    :param content: 正文
    :param recv: 邮箱接收人地址,多个账号以逗号隔开
    :param title: 邮件标题
    :param file: 附件
    :return:
    """
    # localtime = time.localtime(time.time())
    # date = '%d-%02d-%02d' % (localtime.tm_year, localtime.tm_mon, localtime.tm_mday)
    # now_time = ' %02d:%02d' % (localtime.tm_hour, localtime.tm_min)
    # detail_time = date + now_time
    now = datetime.datetime.now()
    detail_time = now.strftime('%Y-%m-%d %H:%M:%S')

    username = '@qq.com'  # 邮箱账号
    passwd = ''  # 邮箱密码
    recv = recv + '@qq.com'
    content = detail_time + content  # 加上时间戳
    mail_host = 'smtp.qq.com'  # 邮箱服务器
    port = 465  # 端口号

    file_handle = open(LOG_FILE, mode='a',  encoding='utf-8')
    file_handle.writelines(detail_time + '\n发送给' + recv + title + ' 正在进行\n')
    file_handle.writelines('——————————————————\n')
    file_handle.close()
    print(detail_time + '\n发送给' + recv + title + ' 正在进行')
    print('——————————————————')

    if file:
        msg = MIMEMultipart()
        # 构建正文
        part_text = MIMEText(content)
        msg.attach(part_text)  # 把正文加到邮件体里面去

        # 构建邮件附件
        part_attach1 = MIMEApplication(open(file, 'rb').read())  # 打开附件
        part_attach1.add_header('Content-Disposition', 'attachment', filename=pathlib.Path(file).name)  # 为附件命名
        msg.attach(part_attach1)  # 添加附件
    else:
        msg = MIMEText(content)  # 邮件内容

    msg['Subject'] = title  # 邮件主题
    msg['From'] = username  # 发送者账号
    msg['To'] = recv  # 接收者账号列表

    count = 0
    while True:

        try:
            if count > 3:
                err_msm()
                break

            smtp = smtplib.SMTP_SSL(mail_host, port=port)
            smtp.connect(mail_host, port=port)
            smtp.login(username, passwd)  # 登录
            smtp.sendmail(username, recv, msg.as_string())
            # smtp.sendmail(username, recv, str(msg))
            smtp.quit()

        except (smtplib.SMTPException or TimeoutError) as err:
            now = datetime.datetime.now()
            detail_time = now.strftime('%Y-%m-%d %H:%M:%S')
            file_handle = open(LOG_FILE, mode='a',  encoding='utf-8')
            file_handle.writelines(detail_time + '\n发送给' + recv + title + ' is failed\n')
            file_handle.writelines(str(err) + '\n')
            file_handle.writelines('——————————————————\n')
            file_handle.close()
            print(detail_time + '\n发送给' + recv + title + ' is failed')
            print(str(err) + '\n')
            print('——————————————————')
            sleep(3)
            count += 1
            continue

        now = datetime.datetime.now()
        detail_time = now.strftime('%Y-%m-%d %H:%M:%S')
        file_handle = open(LOG_FILE, mode='a',  encoding='utf-8')
        file_handle.writelines(detail_time + '\n发送给' + recv + title + ' is succeed\n')
        file_handle.writelines('——————————————————\n')
        file_handle.close()
        print(detail_time + '\n发送给' + recv + title + ' is succeed')
        print('——————————————————')
        break


def email_tip(mark, data):
    mark['email_mark'] = False

    # 学生学号与邮箱联系方式一一对应
    stu_email = {
        
    }

    now = datetime.datetime.now()
    detail_time = now.strftime('%Y-%m-%d %H:%M:%S')
    file_handle = open(LOG_FILE, mode='a',  encoding='utf-8')
    file_handle.writelines(detail_time + '\n开始邮件提醒\n')
    file_handle.writelines('——————————————————\n')
    file_handle.close()
    print(detail_time + "\n开始邮件提醒")
    print('——————————————————')

    if len(data):  # 存在未打卡学生
        for stu in data:
            if stu_email.get(stu['GH']):
                recv = stu_email.get(stu['GH'])
                title = '晚间健康打卡提醒'
                content = '\n[自动邮件,无需回复]\n今日你可能还未进行健康打卡,请注意时间,尽快打卡\n若已打卡,请忽略本条消息\n————软工1903班————'
                # if recv == '':
                send_mail(recv, title, content)
                # 发邮件提醒
    else:
        mark['msm_mark'] = False
        mark['loop_mark'] = False


def send_msm(params):  # 发短信接口
    import zhenzismsclient as smsclient
    # client = smsclient.ZhenziSmsClient(apiUrl, appId, appSecret);
    # apiUrl为请求地址,个人开发者使用https://sms_developer.zhenzikj.com,企业开发者使用https://sms.zhenzikj.com
    # appId:应用id,可通过用户中心,应用详情查看
    # appSecret: 应用秘钥,可通过用户中心,应用详情查看
    apiUrl = 'https://sms_developer.zhenzikj.com'
    appId = ''
    appSecret = ''
    client = smsclient.ZhenziSmsClient(apiUrl, appId, appSecret)

    # localtime = time.localtime(time.time())
    # date = '%d-%02d-%02d' % (localtime.tm_year, localtime.tm_mon, localtime.tm_mday)
    # now_time = ' %02d:%02d' % (localtime.tm_hour, localtime.tm_min)
    # detail_time = date + now_time
    now = datetime.datetime.now()
    detail_time = now.strftime('%Y-%m-%d %H:%M:%S')
    file_handle = open(LOG_FILE, mode='a',  encoding='utf-8')
    file_handle.writelines(detail_time + '\n')
    str1 = '内容:' + ''.join(params.get('templateParams', '管理员提醒'))
    response = client.send(params)
    file_handle.writelines(str1 + response + '\n')
    file_handle.writelines('——————————————————\n')
    file_handle.close()
    print(detail_time + '\n' + str1 + response)
    print('——————————————————')


def msm_tip(mark, data):
    mark['msm_mark'] = False

    now = datetime.datetime.now()
    detail_time = now.strftime('%Y-%m-%d %H:%M:%S')
    file_handle = open(LOG_FILE, mode='a',  encoding='utf-8')
    file_handle.writelines(detail_time + '\n开始短信提醒\n')
    file_handle.writelines('——————————————————\n')
    file_handle.close()
    print(detail_time + "\n开始短信提醒")
    print('——————————————————')

    if len(data):  # 存在未打卡学生
        for stu in data:  # 逐一遍历
            stu_name = stu['XM']  # 姓名
            stu_num = stu['GH']  # 学号
            stu_tel = stu['LXFS']  # 手机号
            now = datetime.datetime.now()
            date = now.strftime('%Y-%m-%d')
            detail_time = now.strftime(' %H:%M:%S')
            params = {'number': stu_tel,
                      'templateId': '3448',
                      'templateParams': [date, detail_time, stu_name, stu_num]
                      # 'templateParams': ['1', '1', '1']
                      }
            if stu_num != '18408010312':
                # if stu_num == '':
                send_msm(params)

    else:
        mark['loop_mark'] = False


def loop_tip(mark, data):
    now = datetime.datetime.now()
    detail_time = now.strftime('%Y-%m-%d %H:%M:%S')
    file_handle = open(LOG_FILE, mode='a',  encoding='utf-8')
    file_handle.writelines(detail_time + '\n开始循环短信提醒\n')
    file_handle.writelines('——————————————————\n')
    file_handle.close()
    print(detail_time + "\n开始循环短信提醒")
    print('——————————————————')

    if len(data):  # 存在未打卡学生
        for stu in data:  # 逐一遍历
            stu_name = stu['XM']  # 姓名
            stu_num = stu['GH']  # 学号
            stu_tel = stu['LXFS']  # 手机号

            params = {'number': stu_tel,
                      'templateId': '3567',
                      'templateParams': [stu_name]
                      }
            if stu_num != '18408010312':
                # if stu_num == '':
                send_msm(params)
    else:
        mark['loop_mark'] = False


def err_msm():
    now = datetime.datetime.now()
    detail_time = now.strftime('%Y-%m-%d %H:%M:%S')

    file_handle = open(LOG_FILE, mode='a',  encoding='utf-8')
    file_handle.writelines(detail_time + '\n出现错误,停止运行\n')
    file_handle.writelines('——————————————————\n')
    file_handle.close()
    print(detail_time + '\n出现错误,请检查')
    print('——————————————————')

    # admin_recv = ''  # 设置管理员邮箱账号,接收汇总情况
    title = '自动打卡程序出错了'  # 汇总邮件内容
    content = "自动打卡程序出错了,请及时查看"
    send_mail(ADMIN_EMAIL, title, content, LOG_FILE)  # 发送错误报告邮件

    params = {'number': ADMIN_TEL,
              'templateId': '3468'
              }
    # self.send_error_msm(params)  # 发送错误报告短信
    send_msm(params)  # 发送错误报告短信

    file_handle = open(LOG_FILE, mode='a',  encoding='utf-8')
    file_handle.writelines(detail_time + '\n发送错误报告\n')
    file_handle.writelines('——————————————————\n')
    file_handle.close()
    print(detail_time + '\n发送错误报告')
    print('——————————————————')


def email_summary(data):
    now = datetime.datetime.now()
    detail_time = now.strftime('%Y-%m-%d %H:%M:%S')

    file_handle = open(LOG_FILE, mode='a',  encoding='utf-8')
    file_handle.writelines(detail_time + '\n发送汇总情况\n')
    file_handle.writelines('——————————————————\n')
    file_handle.close()
    print(detail_time + '\n发送汇总情况')
    print('——————————————————')

    recv = ADMIN_EMAIL
    title = now.strftime('%Y-%m-%d') + '打卡情况'
    if len(data):
        content = '今日未打卡人员(总' + str(len(data)) + '人):\n'
        content = content + "---------------------------------\n"
        content = content + "| 姓名 |  班级  |\n"
        content = content + "---------------------------------\n"
        for stu in data:
            content = content + '| ' + stu['XM'] + ' | ' + stu['SZXKS'] + ' |\n'
            content = content + '---------------------------------\n'
        # 发邮件提醒
        send_mail(recv, title, content)
    else:
        content = '今日已全部打卡完成\n'
        send_mail(recv, title, content)


def query(mark):
    now = datetime.datetime.now()
    delta = datetime.timedelta(days=1)
    date = (now + delta).strftime('%Y-%m-%d')
    url1 = 'http://ehallplatform.xust.edu.cn/default/jkdkgl/mobile/wsbrymx.jsp?uid' \
           '=NTE2RUQ4OTJGREJDRTMxRENFQjZDNEMwNTZBNDgxMjU=&cxsj=' + date + \
           '&cxlx=0&bmid=%274007013%27&bmjb=3'
    url2 = "http://ehallplatform.xust.edu.cn/default/jkdkgl/mobile/" \
           "com.primeton.eos.jkdkgl.WSBRYCX.CXWSBRY.biz.ext"
    jsons = {"bmid": "'4007013'", "cxsj": date, "cxbmjb": "3", "cxlx": "0"}
    # 记录重试次数
    count = 0
    while True:
        # 出错次数大于5退出运行并短信提醒
        if count > 5:
            now = datetime.datetime.now()
            detail_time = now.strftime('%Y-%m-%d %H:%M:%S')
            file_handle = open(LOG_FILE, mode='a',  encoding='utf-8')
            file_handle.writelines(detail_time + '\n网页打开失败\n')
            file_handle.writelines('——————————————————\n')
            file_handle.close()
            print(detail_time + "\n网页打卡失败")
            print('——————————————————')
            err_msm()
            exit(0)

        try:
            session = requests.session()
            # 首次进入,获取随机Cookie
            r = session.get(url1)
            cookie = r.cookies.values()[0]
            header = {
                'Host': 'ehallplatform.xust.edu.cn',
                'Connection': 'keep-alive',
                'Content-Length': '64',
                'Accept': 'application/json, text/plain, */*',
                'Origin': 'http://ehallplatform.xust.edu.cn',
                'X-Requested-With': 'XMLHttpRequest',
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) '
                              'Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3861.400 QQBrowser/10.7.4313.400',
                'Content-Type': 'application/json;charset=UTF-8',
                'Referer': 'http://ehallplatform.xust.edu.cn/default/jkdkgl/mobile/wsbrymx.jsp?uid'
                           '=NTE2RUQ4OTJGREJDRTMxRENFQjZDNEMwNTZBNDgxMjU=&cxsj=2021-03-26&cxlx=0&bmid=%274007013%27'
                           '&bmjb=3',
                'Accept-Encoding': 'gzip, deflate',
                'Accept-Language': 'zh-CN,zh;q=0.9',
                'Cookie': 'JSESSIONID=' + cookie
            }

            response = session.post(url=url2, json=jsons, headers=header)
            # 未打卡人员信息
            data = json.loads(response.text, encoding='utf-8')['data']
        except Exception as err:
            now = datetime.datetime.now()
            detail_time = now.strftime('%Y-%m-%d %H:%M:%S')
            file_handle = open(LOG_FILE, mode='a', encoding='utf-8')
            file_handle.writelines(detail_time + '\n')
            file_handle.writelines(str(err)+'\n')
            file_handle.writelines('——————————————————\n')
            file_handle.close()
            print(detail_time + '\n')
            print(str(err) + '\n')
            print('——————————————————')
            count += 1
            continue
        # 发送汇总情况
        email_summary(data)

        # 提醒方式选择
        if mark['email_mark']:
            # 邮件提醒
            email_tip(mark, data)
        elif mark['msm_mark']:
            # 短信提醒
            msm_tip(mark, data)
        elif mark['loop_mark']:
            # 循环短信提醒
            loop_tip(mark, data)

        break


if __name__ == '__main__':
    # 获取当前时间
    now = datetime.datetime.now()
    # 记录当前日期
    day = now.strftime('%d')
    detail_time = now.strftime('%Y-%m-%d %H:%M:%S')
    file_handle = open(LOG_FILE, mode='w',  encoding='utf-8')
    file_handle.writelines(detail_time + '\n开始运行\n')
    file_handle.writelines('——————————————————\n')
    file_handle.close()
    print(detail_time + "\n开始运行")
    print('——————————————————')

    mark = {
        'email_mark': False,
        "msm_mark": False,
        "loop_mark": False
    }
    # 循环催促时间
    loop_time = '21:00'

    # 根据启动市价调整标志
    if now.strftime('%H:%M') <= '20:00':
        mark['email_mark'] = True
    if now.strftime('%H:%M') <= '20:40':
        mark['msm_mark'] = True
    if now.strftime('%H:%M') <= loop_time:
        mark['loop_mark'] = True
    # 进入循环,到达时间做出相应操作
    while True:
        now = datetime.datetime.now()
        # 时间到达第二天,重置标记
        if day != now.strftime('%d'):
            mark['email_mark'] = True
            mark['msm_mark'] = True
            mark['loop_mark'] = True
            # day = localtime.tm_mday
            day = now.strftime('%d')
            loop_time = '21:00'

        if mark['email_mark'] and now.strftime('%H:%M') == '20:00':
            detail_time = now.strftime('%Y-%m-%d %H:%M:%S')
            file_handle = open(LOG_FILE, mode='a',  encoding='utf-8')
            file_handle.writelines(detail_time + '\n开始第一次查询\n')
            file_handle.writelines('——————————————————\n')
            file_handle.close()
            print(detail_time + "\n开始第一次查询")
            print('——————————————————')
            query(mark)
            now = datetime.datetime.now()
            detail_time = now.strftime('%Y-%m-%d %H:%M:%S')
            file_handle = open(LOG_FILE, mode='a',  encoding='utf-8')
            if mark['msm_mark']:
                file_handle.writelines(detail_time + '\n结束第一次查询,等待第二次查询\n')
                file_handle.writelines('——————————————————\n')
                print(detail_time + "\n结束第一次查询,等待第二次查询")
                print('——————————————————')
            else:
                file_handle.writelines(detail_time + '\n结束第一次查询,已全部打卡\n')
                file_handle.writelines('——————————————————\n')
                print(detail_time + "\n结束第一次查询,已全部打卡")
                print('——————————————————')
            file_handle.close()

        if mark['msm_mark'] and now.strftime('%H:%M') == '20:40':
            detail_time = now.strftime('%Y-%m-%d %H:%M:%S')
            file_handle = open(LOG_FILE, mode='a',  encoding='utf-8')
            file_handle.writelines(detail_time + '\n开始第二次查询\n')
            file_handle.writelines('——————————————————\n')
            file_handle.close()
            print(detail_time + "\n开始第二次查询")
            print('——————————————————')
            query(mark)
            now = datetime.datetime.now()
            detail_time = now.strftime('%Y-%m-%d %H:%M:%S')
            file_handle = open(LOG_FILE, mode='a',  encoding='utf-8')
            if mark['loop_mark']:
                file_handle.writelines(detail_time + '\n结束第二次查询,等待循环催促\n')
                file_handle.writelines('——————————————————\n')
                print(detail_time + "\n结束第二次查询,等待循环催促")
                print('——————————————————')
            else:
                file_handle.writelines(detail_time + '\n结束第二次查询,已全部打卡\n')
                file_handle.writelines('——————————————————\n')
                print(detail_time + "\n结束第二次查询,已全部打卡完成")
                print('——————————————————')
            file_handle.close()

        if mark['loop_mark'] and now.strftime('%H:%M') == loop_time:
            detail_time = now.strftime('%Y-%m-%d %H:%M:%S')
            file_handle = open(LOG_FILE, mode='a',  encoding='utf-8')
            file_handle.writelines(detail_time + '\n开始循环催促\n')
            file_handle.writelines('——————————————————\n')
            file_handle.close()
            print(detail_time + "\n开始循环催促")
            print('——————————————————')
            query(mark)
            now = datetime.datetime.now()
            detail_time = now.strftime('%Y-%m-%d %H:%M:%S')
            file_handle = open(LOG_FILE, mode='a',  encoding='utf-8')
            if mark['loop_mark']:
                delta = datetime.timedelta(minutes=20)
                loop_time = (now + delta).strftime('%H:%M')
                file_handle.writelines(detail_time + "\n还有人未打卡," + loop_time + "时继续催促\n")
                print(detail_time + "\n还有人未打卡," + loop_time + "时继续催促")
                file_handle.writelines('——————————————————')
            else:
                file_handle.writelines(detail_time + "\n结束循环催促,已全部打卡\n")
                file_handle.writelines('——————————————————\n')
                print(detail_time + "\n结束循环催促,已全部打卡")
                print('——————————————————')
            file_handle.close()

        if mark['loop_mark'] and now.strftime('%H:%M') == '23:45':  # 仍然人未打卡,提醒管理员手动发消息
            now = datetime.datetime.now()
            detail_time = now.strftime('%Y-%m-%d %H:%M:%S')
            file_handle = open(LOG_FILE, mode='a',  encoding='utf-8')
            file_handle.writelines(detail_time + '\n仍有人未打卡,向管理员发送短信\n')
            file_handle.writelines('——————————————————\n')
            file_handle.close()
            print(detail_time + '\n仍有人未打卡,向管理员发送短信')
            print('——————————————————')

            params = {'number': ADMIN_TEL,
                      'templateId': '3729'
                      }
            mark['loop_mark'] = False
            send_msm(params)  # 发送管理员提醒短信

        sleep(3)

zhenzismsclient.py(榛子云短信接口)

我用的是榛子云短信平台:官网

import requests
import json
from requests.packages.urllib3.exceptions import InsecureRequestWarning


class ZhenziSmsClient(object):
    def __init__(self, apiUrl, appId, appSecret):
        self.apiUrl = apiUrl
        self.appId = appId
        self.appSecret = appSecret

    def send(self, params):
        data = params;
        data['appId'] = self.appId;
        data['appSecret'] = self.appSecret;
        if 'templateParams' in data:
            data['templateParams'] = json.dumps(data['templateParams']);
        requests.packages.urllib3.disable_warnings(InsecureRequestWarning);
        response = requests.post(self.apiUrl + '/sms/v2/send.do', data=data, verify=False);
        result = str(response.content, 'utf-8');
        return result;

    def balance(self):
        data = {
            'appId': self.appId,
            'appSecret': self.appSecret
        }
        requests.packages.urllib3.disable_warnings(InsecureRequestWarning);
        response = requests.post(self.apiUrl + '/account/balance.do', data=data, verify=False);
        result = str(response.content, 'utf-8');
        return result;

    def findSmsByMessageId(self, messageId):
        data = {
            'appId': self.appId,
            'appSecret': self.appSecret,
            'messageId': messageId
        }
        requests.packages.urllib3.disable_warnings(InsecureRequestWarning);
        response = requests.post(self.apiUrl + '/smslog/findSmsByMessageId.do', data=data, verify=False);
        result = str(response.content, 'utf-8');
        return result;


七、总结

这个程序是我自己独立完成的一个较大的Python爬虫程序,很有纪念意义,我从中也学到了很多东西,在此记录下来。关于遇到的问题,下一篇博文慢慢分析。

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值