1.tornado

一个精简的异步爬虫(来自tornado的demo)

#!/usr/bin/env python

import time
from datetime import timedelta try:
from HTMLParser import HTMLParser
from urlparse import urljoin, urldefrag
except ImportError:
from html.parser import HTMLParser
from urllib.parse import urljoin, urldefrag from tornado import httpclient, gen, ioloop, queues base_url = 'http://www.tornadoweb.org/en/stable/'
concurrency = 10 @gen.coroutine
def get_links_from_url(url):
"""Download the page at `url` and parse it for links.
Returned links have had the fragment after `#` removed, and have been made
absolute so, e.g. the URL 'gen.html#tornado.gen.coroutine' becomes
'http://www.tornadoweb.org/en/stable/gen.html'.
"""
try:
response = yield httpclient.AsyncHTTPClient().fetch(url)
print('fetched %s' % url) html = response.body if isinstance(response.body, str) \
else response.body.decode()
urls = [urljoin(url, remove_fragment(new_url))
for new_url in get_links(html)]
except Exception as e:
print('Exception: %s %s' % (e, url))
raise gen.Return([]) raise gen.Return(urls) def remove_fragment(url):
pure_url, frag = urldefrag(url)
return pure_url def get_links(html):
class URLSeeker(HTMLParser):
def __init__(self):
HTMLParser.__init__(self)
self.urls = [] def handle_starttag(self, tag, attrs):
href = dict(attrs).get('href')
if href and tag == 'a':
self.urls.append(href) url_seeker = URLSeeker()
url_seeker.feed(html)
return url_seeker.urls @gen.coroutine
def main():
q = queues.Queue()
start = time.time()
fetching, fetched = set(), set() @gen.coroutine
def fetch_url():
current_url = yield q.get()
try:
if current_url in fetching:
return print('fetching %s' % current_url)
fetching.add(current_url)
urls = yield get_links_from_url(current_url)
fetched.add(current_url) for new_url in urls:
# Only follow links beneath the base URL
if new_url.startswith(base_url):
yield q.put(new_url) finally:
q.task_done() @gen.coroutine
def worker():
while True:
yield fetch_url() q.put(base_url) # Start workers, then wait for the work queue to be empty.
for _ in range(concurrency):
worker()
yield q.join(timeout=timedelta(seconds=300))
assert fetching == fetched
print('Done in %d seconds, fetched %s URLs.' % (
time.time() - start, len(fetched))) if __name__ == '__main__':
import logging
logging.basicConfig()
io_loop = ioloop.IOLoop.current()
io_loop.run_sync(main)

2.tornado的定时回调

from tornado import ioloop
import datetime period = 5 * 1000 # every 5 s def like_cron():
print datetime.datetime.now() def xiaorui():
print 'call xiaorui.cc 2s' def lee():
print 'call lee 3s' if __name__ == '__main__':
ioloop.PeriodicCallback(like_cron, 3000).start() # start scheduler
# ioloop.PeriodicCallback(lee, 3000).start()
ioloop.IOLoop.instance().start()

一些爬虫中的snippet的更多相关文章

  1. 手把手教你写Sublime中的Snippet

    手把手教你写Sublime中的Snippet Sublime Text号称最性感的编辑器, 并且越来越多人使用, 美观, 高效 关于如何使用Sublime text可以参考我的另一篇文章, 相信你会喜 ...

  2. 采集爬虫中,解决网站限制IP的问题? - wendi_0506的专栏 - 博客频道 - CSDN.NET

    采集爬虫中,解决网站限制IP的问题? - wendi_0506的专栏 - 博客频道 - CSDN.NET undefined

  3. crawler_网络爬虫中编码的正确处理与乱码的解决策略

    转载: http://hi.baidu.com/erliang20088/item/9156132bdaeae8949c63d134 最近一个月一直在对nutch1.6版进行中等层次的二次开发,本来是 ...

  4. 跟着太白老师学python day11 闭包 及在爬虫中的基本使用

    闭包的基本概念: 闭包 内层函数对外层函数的变量(不包括全局变量)的引用,并返回,这样就形成了闭包 闭包的作用:当程序执行时,遇到了函数执行,它会在内存中开辟一个空间,如果这个函数内部形成了闭包, 那 ...

  5. 爬虫中之Requests 模块的进阶

    requests进阶内容 session处理cookie proxies参数设置请求代理ip 基于线程池的数据爬取 引入 有些时候,我们在使用爬虫程序去爬取一些用户相关信息的数据(爬取张三“人人网”个 ...

  6. asyncio在爬虫中的使用

    # -*- coding: utf-8 -*- # 协程基础.py import asyncio import time async def request(url): print("正在请 ...

  7. crawler_JVM_DNS_在爬虫中的应用

    DNS解析:即由域名 经过dns解析,跳转到真正服务器的地址,这个重复解析的耗时占请求很大比例. 在设计爬虫时比较细粒度的控制下,需要考虑dns解析. jdk从1.5往后对dns缓存有默认设置, 详见 ...

  8. python爬虫中scrapy框架是否安装成功及简单创建

    判断框架是否安装成功,在新建的爬虫文件夹下打开盘符中框输入cmd,在命令中输入scrapy,若显示如下图所示,则说明成功安装爬虫框架: 查看当前版本:在刚刚打开的命令框内输入scrapy versio ...

  9. 网络爬虫中Fiddler抓取PC端网页数据包与手机端APP数据包

    1 引言 在编写网络爬虫时,第一步(也是极为关键一步)就是对网络的请求(request)和回复(response)进行分析,寻找其中的规律,然后才能通过网络爬虫进行模拟.浏览器大多也自带有调试工具可以 ...

随机推荐

  1. hdu1054 Strategic Game 树形DP

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1054 思路:树形DP,用二分匹配也能解决 定义dp[root][1],表示以root 为根结点的子树且 ...

  2. [刷题]算法竞赛入门经典(第2版) 6-1/UVa673 6-2/UVa712 6-3/UVa536

    这三题比较简单,只放代码了. 题目:6-1 UVa673 - Parentheses Balance //UVa673 - Parentheses Balance //Accepted 0.000s ...

  3. Spring3.0配置多个事务管理器(即操作多个数据源)的方法

    大多数项目只需要一个事务管理器.然而,有些项目为了提高效率.或者有多个完全不同又不相干的数据源,最好用多个事务管理器.机智的Spring的Transactional管理已经考虑到了这一点,首先分别定义 ...

  4. 配置nginx脚本开机自启动

    vi /etc/init.d/nginx 插入以下内容,修改红色字体自己安装路径 #!/bin/bash## chkconfig: - 85 15# description: Nginx is a W ...

  5. SharePoint 无法删除搜索服务应用程序

    在SharePoint的使用中,经常会遇到某些服务创建失败,某些服务删除不成功的情况.这里,我们就遇到了搜索服务创建失败,然后删除也不成功,使用管理中心的UI无法删除,PowerShell命令也无法删 ...

  6. php+ajax发起流程和审核流程(以请假为例)

    上一篇随笔中已经提到如何新建流程,那么现在我们就来看一下如何发起一个流程和审核流程~~~ 先说一下思路: (1)登录用session获取到用户的id (2) 用户发起一个流程 注意:需要写申请事由 ( ...

  7. 【js实例】js中的5种基本数据类型和9种操作符

    js中的5中基本数据类型 js标识符 第一个字符必须为字母,下划线,或美元符 其他字符可以是字母,下划线,美元符,数字 js标识符区分大小写 标识符不能使关键字和保留字 关键字: break do i ...

  8. SmartCoder每日站立会议 01

    1.站立会议内容 确定今天团队成员各自的任务,并讨论今后各自的学习方向. 站立会议照片: 2.任务看板: 3.燃尽图:

  9. Fiddler中如何抓取app中https(443端口)数据

    Fiddler不但能截获各种浏览器发出的HTTP请求, 也可以截获手机发出的HTTP/HTTPS请求,总结下Fiddler截获IPhone和Android发出的HTTP/HTTPS包,前提条件是:安装 ...

  10. jQuery对象的创建(一)

    在jQuery的常规用法中,执行"$()"返回的是一个jQuery对象,在源码中,它是这样定义的: ... var jQuery = function() { return new ...