Python数据入门网络爬虫

女神微博监控实现

2017-05-04  本文已影响582人  nonoBoy

用到的知识:
1、网络爬虫模块:每过1分钟爬一次牙牙的微博,有内容更新则通过邮件发送提醒自己;
2、自动发送邮件模块:爬虫代码和发送邮件的代码都放在云服务器上24小时运行

爬虫代码:

import requests
from lxml import etree
import time
import random

headers = {
    'User-Agent': 'Avant Browser/1.2.789rel1 (http://www.avantbrowser.com)',
    'Cookie': '你的cookie'
}

#定义获取第一条微博的函数
def getContents(url):
    #需要完善 异常处理
    response = requests.get(url, headers = headers)
    selector = etree.HTML(response.content) 
    #查看html源码可以找到微博内容+ 发布时间的结构 用xpath解析
    all_cont = selector.xpath("//span[@class='ctt']")
    all_times = selector.xpath("//span[@class='ct']")
    #解析出最新微博的发布时间
    time1 = all_times[0].xpath('string(.)')
    #解析出第一条微博内容 注意这里取第2或者第3个元素(具体视是否有个人介绍)
    con3= all_cont[2].xpath('string(.)')  

    print(con3 + "发布时间:"+ time1[0:3])

    if time1[:3] == '1分钟':
        print('1分钟内更新了.....')
        #更新了则发送邮件通知
        context = '更新内容为:'+con3
        #调用发送邮件的函数
        send("收件邮箱地址", "女神微博更新啦~~", context)
    else:
        print('还未更新......')

#延时函数 大概1分钟抓取1次
def delay():
    delay = 59 + random.random()  
    time.sleep(delay)

#女神微博地址 额 其实是男神
url = 'https://weibo.cn/3526653435/profile'

#让代码在服务器上一直跑着 
while True:
    getContents(url)
    delay()

发送邮件的函数模块(代码):

from email.mime.text import MIMEText
import smtplib

account = "forXXXX@gmail.com"
password = "你的邮箱密码"

def send(to, title, content):
    smtp_port = 587 
    server = smtplib.SMTP('smtp.googlemail.com', smtp_port)
    server.docmd("EHLO server")
    server.starttls()
    server.set_debuglevel(1)
    server.login(account, password)

    msg = MIMEText(content)
    msg['Content-Type'] = 'text/plain; charset="utf-8"'
    msg['Subject'] = title
    msg['From'] = account
    msg['To'] = to
    server.sendmail(account, to, msg.as_string())
    server.close()

输出:

我来北京了 ​​​发布时间:05月
还未更新......

#更新了微博
我又来测试了 ​​​发布时间:1分钟
1分钟内更新了.....

测试邮箱页收到提示


1.png
上一篇 下一篇

猜你喜欢

热点阅读