跟着某乎玩python(四)

xpath抓取天气存入数据库并定时自动发送邮件脚本

本篇“玩python”来源答主链接:

None
爬虫知识from:知乎live 《爬虫从入门到进阶》—董伟明

环境配置:

1.系统环境:Windows 7 64bit
2.编译环境:Python3.4.3
3.依赖库: requests lxml pymysql logging time apscheduler smtplib
4.其他工具:Chrome浏览器
5.前置条件:已安装mysql、mysql已配置支持中文插入、mysql中已创建database TESTDB、两个可用邮箱,其中发送邮箱开启STMP服务

代码浅析

流程图

Created with Raphaël 2.1.0 数据库中创建table 创建定时任务 是否到时 从网页获取天气 存入数据库 发送邮件 wait yes no

获取天气

如图所示,使用Chrome浏览器检查,找到所需要的信息

图中圈出的就是所需的信息简报,当然也可从该页面其他地方读取,这个可以随意选择。

爬天气demo

def get_weather(url):
    headers = {
        'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36'
    }
    try:
        response=requests.get(NanJiWEATHER_URL,headers=headers) 
        if response.status_code == 200:
            logging.debug(response.encoding)
            logging.debug(response.apparent_encoding)
            r = response.text
            rr = r.encode('ISO-8859-1').decode(response.apparent_encoding
            tree = html.fromstring(rr)
            el=tree.xpath('//div[@id="7d"]//input[@type="hidden"]')
            logging.debug(el[0].value)
            logging.debug(len(el[0].value))
            return el[0].value
        return None
    except RequestException:
        logging.debug('load weather failed')
        return None

header伪装不再提,状态码前面也是出现过,值得一提的是xpath,请特别注意这种书写格式,一开始用起来非常不习惯,但是多用几次发现,使用xpath来找自己想要的东西实在太方便太方便,如果你bs用的不熟,如果re也用的不熟,强烈推荐xapth。这段代码在调试时遇到的坑就编码问题,request返回的response默认encoding是ISO-8859-1,打印出来是满屏的乱码,转化成utf-8才不会乱,那这里就是Python2和python3之间的编码差异,要了解什么时候数据是byte?什么时候是str?网上有一堆的资料,这里不再赘述。

发送邮件

my_sender='[email protected]'#发送方     
my_pass = '*********'          #邮件密码              
my_user='[email protected]'     #接收方
def mail(maintext):
    ret=True
    try:
        msg=MIMEText(maintext,'plain','utf-8')
        msg['From']=formataddr(["FromPG's script",my_sender]) 
        msg['To']=formataddr(["FK",my_user])             
        msg['Subject']="Script send email"               
        server=smtplib.SMTP_SSL("smtp.exmail.qq.com", 465) 
        server.login(my_sender, my_pass) 
        server.sendmail(my_sender,[my_user,],msg.as_string())  
        server.quit()  
    except Exception:  
        ret=False
    return ret

这部分demo我承认,是抄来的- -,可耻的搬运工说的就是我!
看详情请狂点这里:
菜鸟教程:Python SMTP发送邮件

定时任务模块

python可以实现定时任务有以下几种方式

1.循环sleep
2.threading的Timer
3.sched模块
4.定时框架APScheduler

荐读:
Python定时任务的实现方式
这里贴出简单的使用例子

from datetime import datetime
import time
from apscheduler.schedulers.blocking import BlockingScheduler

def job():
    print(datetime.now().strftime("%y-%m-%d %H:%M:%S"))
scheduler = BlockingScheduler()
scheduler.add_job(job,'cron',day_of_week='1-6',hour=14,minute=59)
scheduler.start()

完整代码点这里

回顾与总结

  • 小小的一个脚本涉及的知识点还不少,mysql基本的增删查改,xpath爬虫,stmp服务发送邮件,python定时任务。
  • 这个小项目耗时较长,主要代码不再是以前复制粘贴或者照抄照搬一个个打过来,而是照着live第一节学完,再自己实现。
  • 为知识付费很必要,为自己的成长投资才是最好的投资。
  • 学会使用检索引擎,网速允许的话,请google而非baidu。
  • 加班再忙,就算出差奔波也不能停止学习和健身。come on pg

猜你喜欢

转载自blog.csdn.net/qq_30650153/article/details/78927449