import time
import logging
from datetime import timedelta
from tornado import httpclient, gen, ioloop, queues
import traceback
def logged(class_):
logging.basicConfig(level=logging.INFO)
class_.logger = logging.getLogger(class_.__name__)
return class_
@logged
class AsyncSpider(object):
"""A simple class of asynchronous spider."""
def __init__(self, urls, concurrency=10, results=None, **kwargs):
super(AsyncSpider, self).__init__(**kwargs)
self.concurrency = concurrency
self._q = queues.Queue()
self._fetching = set()
self._fetched = set()
if results is None:
self.results = []
for url in urls:
self._q.put(url)
httpclient.AsyncHTTPClient.configure(
"tornado.curl_httpclient.CurlAsyncHTTPClient"
)
def fetch(self, url, **kwargs):
fetch = getattr(httpclient.AsyncHTTPClient(), 'fetch')
http_request = httpclient.HTTPRequest(url, **kwargs)
return fetch(http_request, raise_error=False)
def handle_html(self, url, html):
"""处理html页面"""
print(url)
def handle_response(self, url, response):
"""处理http响应,对于200响应码直接处理html页面,
否则按照需求处理不同响应码"""
if response.code == 200:
self.handle_html(url, response.body)
elif response.code == 599: # retry
self._fetching.remove(url)
self._q.put(url)
@gen.coroutine
def get_page(self, url):
# yield gen.sleep(10) # sleep when need
try:
response = yield self.fetch(url)
self.logger.debug('######fetched %s' % url)
except Exception as e:
self.logger.debug('Exception: %s %s' % (e, url))
raise gen.Return(e)
raise gen.Return(response) # py3 can just return response
@gen.coroutine
def _run(self):
@gen.coroutine
def fetch_url():
current_url = yield self._q.get()
try:
if current_url in self._fetching:
return
self.logger.debug('fetching****** %s' % current_url)
self._fetching.add(current_url)
response = yield self.get_page(current_url)
self.handle_response(current_url, response) # handle reponse
self._fetched.add(current_url)
finally:
self._q.task_done()
@gen.coroutine
def worker():
while True:
yield fetch_url()
# Start workers, then wait for the work queue to be empty.
for _ in range(self.concurrency):
worker()
yield self._q.join(timeout=timedelta(seconds=300000))
try:
assert self._fetching == self._fetched
except AssertionError: # some http error not handle
print(self._fetching-self._fetched)
print(self._fetched-self._fetching)
def run(self):
io_loop = ioloop.IOLoop.current()
io_loop.run_sync(self._run)
class MySpider(AsyncSpider):
def fetch(self, url, **kwargs):
"""重写父类fetch方法可以添加cookies,headers,timeout等信息"""
cookies_str = "PHPSESSID=j1tt66a829idnms56ppb70jri4; pspt=%7B%22id%22%3A%2233153%22%2C%22pswd%22%3A%228835d2c1351d221b4ab016fbf9e8253f%22%2C%22_code%22%3A%22f779dcd011f4e2581c716d1e1b945861%22%7D; key=%E9%87%8D%E5%BA%86%E5%95%84%E6%9C%A8%E9%B8%9F%E7%BD%91%E7%BB%9C%E7%A7%91%E6%8A%80%E6%9C%89%E9%99%90%E5%85%AC%E5%8F%B8; think_language=zh-cn; SERVERID=a66d7d08fa1c8b2e37dbdc6ffff82d9e|1444973193|1444967835; CNZZDATA1254842228=1433864393-1442810831-%7C1444972138"
headers = {
'User-Agent': 'mozilla/5.0 (compatible; baiduspider/2.0; +http://www.baidu.com/search/spider.html)',
'cookie': cookies_str
}
return super(MySpider, self).fetch(
url, headers=headers,
#proxy_host="127.0.0.1", proxy_port=8787, # for proxy
)
def handle_html(self, url, html):
print(url)
#print(BeautifulSoup(html, 'lxml').find('title'))
def main():
st = time.time()
urls = []
n = 1000
for page in range(1, n):
urls.append('http://www.jb51.net/article/%s.htm' % page)
s = MySpider(urls, 10)
s.run()
print(time.time()-st)
print(60.0/(time.time()-st)*1000, 'per minute')
print(60.0/(time.time()-st)*1000/60.0, 'per second')
if __name__ == '__main__':
main()
没有合适的资源?快使用搜索试试~ 我知道了~
温馨提示
探索Python爬虫工具:为数据挖掘与数据分析提供强大支持 在数据驱动的今天,获取并处理数据是每个研究人员、数据分析师和企业的重要任务。为此,我们汇集了一系列Python爬虫工具,旨在帮助您更高效地获取、处理和分析网络数据。 内容概览 这个压缩包集合包括了从单一用途到多功能的各种Python爬虫工具。无论您是需要快速抓取特定网站的数据,还是希望构建复杂的网络爬虫来处理大量数据,这里都有适合您的工具。 为何选择我们的Python爬虫工具 实用性: 这些工具都是根据实际需求开发的,具有高度的实用性和针对性,能帮助您解决实际问题。 易用性: 无需复杂的设置,即插即用,让您专注于数据获取和分析,而不是工具的配置。 高效性: 这些工具利用了Python的强大功能,能够快速、准确地抓取数据。 可扩展性: 每个工具都具有良好的扩展性,可以根据您的具体需求进行定制。 如何使用这些工具 每个工具都附带了详细的文档和示例,帮助您快速上手。对于更深入的使用,我们提供了在线支持和社区论坛,方便您与其他用户交流和学习。 下一步行动 现在就下载这些Python爬虫工具,开始您的数据获取之旅!为数据科学、网络挖掘和分析提供强大的支持,满足您的所有需求。
资源推荐
资源详情
资源评论
收起资源包目录
Python爬虫工具库(异步爬虫类、线程池爬虫类、爬虫实用函数).zip (4个子文件)
meyangyangshenglexiaohuihui
utils.py 4KB
__init__.py 324B
threadpool_spider.py 2KB
tornado_spider.py 4KB
共 4 条
- 1
资源评论
01红C
- 粉丝: 1637
- 资源: 1098
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
最新资源
- pta题库答案c语言之排序4统计工龄.zip
- pta题库答案c语言之树结构7堆中的路径.zip
- pta题库答案c语言之树结构3TreeTraversalsAgain.zip
- pta题库答案c语言之树结构2ListLeaves.zip
- pta题库答案c语言之树结构1树的同构.zip
- 基于C++实现民航飞行与地图简易管理系统可执行程序+说明+详细注释.zip
- pta题库答案c语言之复杂度1最大子列和问题.zip
- 三维装箱问题(Three-Dimensional Bin Packing Problem,3D-BPP)是一个经典的组合优化问题
- 以下是一些关于Linux线程同步的基本概念和方法.txt
- 以下是一个简化的示例,它使用pygame库来模拟烟花动画的框架.txt
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功