博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【python】使用简单的python语句编写爬虫 定时拿取信息并存入txt
阅读量:7044 次
发布时间:2019-06-28

本文共 1381 字,大约阅读时间需要 4 分钟。

爬虫脚本 echo2.py

# -*- coding: utf-8 -*-    #解决编码问题import urllibimport urllib2import reimport osimport time page = 1url = 'http://www.qiushibaike.com/text/page/4/?s=4970196'     #爬取的目标网站user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'headers = { 'User-Agent' : user_agent }try:    request = urllib2.Request(url,headers = headers)    response = urllib2.urlopen(request)    # print response.read()    content = response.read().decode('utf-8')  #解决编码问题    pattern = re.compile(r'
(.*?).*?',re.S) #第一个参数是匹配要爬取的内容,这里使用正则去匹配 items = re.findall(pattern,content) f=open(r'.\article.txt','ab') #txt文件路径 nowTimes = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())) #获取当前时间 f.write('时间:{}\n\n'.format(nowTimes),); #txt文件中写入时间 for i in items: i.encode('utf-8') agent_info = u''.join(i).encode('utf-8').strip() f.writelines('段子:%s%s\n'%(str(agent_info),os.linesep)) #分行存入 # f.write('%s'%str(agent_info)) f.close() # print items except urllib2.URLError, e: if hasattr(e,"code"): print e.code if hasattr(e,"reason"): print e.reason复制代码

布置定时任务使用crontab。 (具体crontab使用方法可见http://blog.csdn.net/daivon_up/article/details/71266814):

* */1 * * * /usr/bin/python /home/dengwen/desktop/echo2.py复制代码

运行结果:

本篇文章如对您有用,欢迎~,谢谢!

转载于:https://juejin.im/post/5cea1733e51d455a694f9494

你可能感兴趣的文章
聊聊UIView
查看>>
mysql主从
查看>>
Linux系统下转换文件编码的方法
查看>>
Excle百万数据量 导出
查看>>
云盘参数和性能测试方法
查看>>
Web前端——链接和表格使用规范
查看>>
2.6.18 32位环境 src.rpm包的使用
查看>>
Windows服务创建及安装
查看>>
Python27+Opencv3 VideoCapture FALSE问题记录
查看>>
如何在 Linux 系统查询机器最近重启时间
查看>>
jQuery插件学习(二)
查看>>
Ajax (部分一)自己做的,总结页面向后台传Form值、单个值和后台向前台传一个或是一组值...
查看>>
web缓存技术
查看>>
集合知识点
查看>>
Linux快捷键
查看>>
文档对象模型DOM
查看>>
2019北京国际康复及个人健康博览会将在中国国际展览中心举办
查看>>
JVM——类加载机制(一)
查看>>
超清晰的 DNS 原理入门指南 (资源)
查看>>
大神笔记
查看>>