python静态网页爬虫之xpath(简单的博客更新提醒功能)
2016-05-24 10:05
603 查看
直接上代码:
#!/usr/bin/env python3 #antuor:Alan #-*- coding: utf-8 -*- import requests from lxml import etree import datetime,time import os class xxoohelper(object): #易读 def __init__(self): self.url = 'http://www.cnblogs.com/alan-babyblog/' #初始化 def getSource(self): html = requests.get(self.url).content #content比text好用,一个返回的是byte,一个返回的是str return html def getContent(self,html): #先大后小 selector = etree.HTML(html) title = selector.xpath('//div[1]/div[2]/a/text()')[0].strip() #从列表提取文本 content = selector.xpath('//div[1]/div[2]/div[1]/div/div[1]/div[3]/div/text()')[0].strip() post_time = selector.xpath('//div[1]/div[2]/div[1]/div/div[1]/div[5]/text()')[0].strip() send_text = title+content+post_time #类型是str return send_text def tosave(self,text): with open('myblog.txt','a') as f: f.write(('{0}\n').format(text)) #换行 def tocheck(self,data): if not os.path.exists('myblog.txt'): #判断是否存在文件 return True else: with open ('myblog.txt','r') as f: existblog = f.readlines() #print(data+'\n') if data +'\n' in existblog: #判断是否已经纪录过内容 return False else: return True if __name__ == '__main__': #程序入口 helper = xxoohelper() #实例化 while True : #while循环不断监控页面 source = helper.getSource() content = helper.getContent(source) if helper.tocheck(content): post_time = str(datetime.datetime.now()) print(post_time,'有新内容\n',content) helper.tosave(content) else: print('扫描中......') pass time.sleep(30)
相关文章推荐
- arcgis9.3 执行python文件
- python之集合,函数,装饰器
- PYthon投票程序段以及sorted函数说明
- python中异常处理之esle,except,else
- Python爬虫和情感分析简介
- mysql-python
- Python中super
- python学习05-映射和集合类型
- pip的常用操作
- 关于用burp抓取python上网信息的使用方法
- Spark RDD操作(Python)总结
- Error generating Swagger server (Python Flask) from Swagger editor
- python 磁力链接搜索器
- win7 64 安装mysql-python:_mysql.c(42) : fatal error C1083: Cannot open include file: 'config-win.h': No such file or directory
- python爬虫:案例三:去哪儿酒店价格信息
- 关于 Python Iterator 协议的一点思考
- Python 正则表达式里面 贪婪模式和非贪婪模式的区别
- 决策树原理-python实现
- 1.python的第一步
- Python实现二叉树结构与进行二叉树遍历的方法详解