使用简单的python语句编写爬虫 定时拿取信息并存入txt

echo2.py

# -*- coding: utf-8 -*-    #解决编码问题
import urllib
import urllib2
import re
import os
import time
 
page = 1
url = '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'<div.*?class="content".*?<span>(.*?)</span>.*?</div>',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

####运行结果:
运行结果

如果觉得我的文章对你有帮助,欢迎关注我的blog

相关知识点

【Javascript】深入理解async/await的实现,Generator+Promise = Async/Await
【Javascript】深入理解this作用域问题以及new运算符对this作用域的影响
【Javascript】手写运算符new创建实例并实现js继承

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值