import aiohttp
import asyncio
import async_timeout
from urllib.parse import urljoin,urldefrag root_url = 'http://python/org/' # 开始的url
crawled_urls,url_hub = [], [root_url]
headers = {'user-agent': 'Opera/9.80 (X11; Linux x86_64; U; en) Presto/2.2.15 Version/10.10'} async def get_body(url):
async with aiohttp.ClientSession() as session:
try:
with async_timeout.timeout(10): #超时时间的设定
async with session.get(url,headers=headers) as response:
if response.status == 200:
html = await response.text()
return {'error':'','html':html,'url':url}
else:
return {'error':response.status,'html':'','url':url}
except Exception as err:
return {'error':response.status,'html':'','url':url} async def handle_task(task_id,work_queue):
while not work_queue.empty():
queue_url = await work_queue.get()
if not queue_url in crawled_urls: body = await get_body(queue_url)
if not body['error']:
crawled_urls.append(queue_url)
parse(body)
else:
print('{}爬取失败'.format(queue_url)) #解析返回的数据
def parse(body):
pass def remove_fragment(url):
pure_url, frag = urldefrag(url)
return pure_url #解析html,拼接新的url
def get_urls(html):
new_urls = [url.split('"')[0] for url in str(html).replace("'", '"').split('href="')[1:]]
return [urljoin(root_url, remove_fragment(new_url)) for new_url in new_urls] if __name__ == '__main__':
q = asyncio.Queue() #初始化一个异步的队列
[q.put_nowait(url) for url in url_hub] #从初始的url队列中遍历,把url放入到队列中
loop = asyncio.get_event_loop()
tasks = [handle_task(task_id, q) for task_id in range(3)] #3个并发
loop.run_until_complete(asyncio.wait(tasks))
loop.close()
for u in crawled_urls:
print(u)
print('-' * 30)
print(len(crawled_urls))

aiohttp的模板的更多相关文章

  1. PYTHON --WebAPP项目转载(廖雪峰) -- Day 1 -- 搭建开发环境

    Day 1 - 搭建开发环境   搭建开发环境 首先,确认系统安装的Python版本是3.5.x: $ python3 --version Python 3.5.1 然后,用pip安装开发Web Ap ...

  2. aiohttp爬虫的模板,类的形式

    import asyncio import aiohttp import async_timeout from lxml import html from timeit import default_ ...

  3. python3异步爬虫 ——aiohttp模板使用

    一.简单使用和讲解 import aiohttp import asyncio async def fetch(client): async with client.get('http://httpb ...

  4. aiohttp笔记

    目录 简介 采集模板 一批,一次性采集 动态添加任务 动态添加任务,封装成类 简介 aiohttp需要python3.5.3以及更高的版本,它不但能做客户端爬虫,也能做服务器端,利用asyncio,协 ...

  5. python web开发 框架 模板 MVC

    我是跟着廖雪峰老师学习的,对于我这样的纯小白来说,跟着他的网站学习,简直是被妈妈抱在怀里一样无忧无虑,这样的学习本来没有记录下来的必要,但是由于我的粗心大意,经常会出现一些错误,所以我决定把这些错误记 ...

  6. Jade模板引擎让你飞

    写在前面:现在jade改名成pug了 一.安装 npm install jade 二.基本使用 1.简单使用 p hello jade! 渲染后: <p>hello jade!</p ...

  7. ABP入门系列(2)——通过模板创建MAP版本项目

    一.从官网创建模板项目 进入官网下载模板项目 依次按下图选择: 输入验证码开始下载 下载提示: 二.启动项目 使用VS2015打开项目,还原Nuget包: 设置以Web结尾的项目,设置为启动项目: 打 ...

  8. CMS模板应用调研问卷

    截止目前,已经有数十家网站与我们合作,进行了MIP化改造,在搜索结果页也能看到"闪电标"的出现.除了改造方面的问题,MIP项目组被问到最多的就是:我用了wordpress,我用了织 ...

  9. PHP-自定义模板-学习笔记

    1.  开始 这几天,看了李炎恢老师的<PHP第二季度视频>中的“章节7:创建TPL自定义模板”,做一个学习笔记,通过绘制架构图.UML类图和思维导图,来对加深理解. 2.  整体架构图 ...

随机推荐

  1. leetcode Ch2-Dynamic Programming II

    一. Longest Valid Parentheses 方法一.一维DP class Solution { public: int longestValidParentheses(string s) ...

  2. [翻译] MSAlertController

    MSAlertController You can use AlertController in iOS7!! 你可以在iOS中使用AlertController了 MSAlertController ...

  3. 用setTimeout实现动态时钟的效果

    1.获取到系统时间 2.获取到当地时间字符串 3.开启延时器,每一秒刷新一次时间 <!DOCTYPE html> <html> <head> <meta ch ...

  4. css动画 文字闪烁效果

    /*定义页面基础CSS*/ body{ font-family: 'microsoft yahei',Arial,sans-serif; color: #EFEFEF; background: #22 ...

  5. python windows 远程执行bat

    本机环境:Win 10,python3.6 远程机器: Win7.WinServer 因python在windows上执行需要用到 wmi 模块. wmi 模块下载地址:https://sourcef ...

  6. Chapter 2 Secondary Sorting:Detailed Example

    2.1 Introduction MapReduce framework sorts input to reducers by key, but values of reducers are arbi ...

  7. JavaScript 变量声明提升

    JavaScript 变量声明提升 一.变量提升的部分只是变量的声明,赋值语句和可执行的代码逻辑还保持在原地不动 二.在基本的语句(或者说代码块)中(比如:if语句.for语句.while语句.swi ...

  8. programming-languages学习笔记--第6部分

    programming-languages学习笔记–第6部分 */--> pre.src {background-color: #292b2e; color: #b2b2b2;} program ...

  9. Nginx之动静分离

    为什么要动静分离呢? 拿Nginx来说,Nginx是Web服务器,仅仅只能处理静态资源(例如js,img,css等等),而Tomcat属于应用服务器既能处理静态资源又能处理动态资源(例如jsp,fre ...

  10. SpringBoot实战(九)之Validator

    表单验证,是最为常见的,今天演示的是利用hibernate-validtor进行校验,有的时候,虽然前端方面通过jQuery或者require.js校验框架进行校验,可以减轻服务器的压力和改善用户体验 ...