爬虫模块之解决IO
一 asyncio模块
asyncio模块:主要是帮我们检测IO(只能是网路IO)。
@asyncio.coroutine:装饰器
tasks:任务列表
get_event_loop:起任务
run_until_complete:提交的方式,检测任务的执行
asgncio.gather(任务列表):直接执行任务
close:关闭任务
open_connection:建立链接
yield from:如果阻塞就切换到另外一个任务
sleep:模仿网络阻塞IO
write:将数据包准备好
send.drain:发送数据包
read:接收数据
# import asyncio
#
# @asyncio.coroutine
# def task(task_id,senconds):
# print('%s is runing' %task_id)
# yield from asyncio.sleep(senconds)
# print('%s is done' %task_id)
#
#
# tasks=[
# task(1,3),
# task(2,2),
# task(3,1)
# ]
#
# loop=asyncio.get_event_loop()
# loop.run_until_complete(asyncio.gather(*tasks))
# loop.close() #1、按照TCP:建立连接(IO阻塞)
#2、按照HTTP协议:url,请求方法,请求头,请求头
#3、发送Request请求(IO)
#4、接收Respone响应(IO)
import asyncio @asyncio.coroutine
def get_page(host,port=80,url='/'): #https:// www.baidu.com:80 /
print('GET:%s' %host)
recv,send=yield from asyncio.open_connection(host=host,port=port) http_pk="""GET %s HTTP/1.1\r\nHost:%s\r\n\r\n""" %(url,host)
send.write(http_pk.encode('utf-8')) yield from send.drain() text=yield from recv.read() print('host:%s size:%s' %(host,len(text))) #解析功能 #http://www.cnblogs.com/linhaifeng/articles/7806303.html
#https://wiki.python.org/moin/BeginnersGuide
#https://www.baidu.com/ tasks=[
get_page('www.cnblogs.com',url='/linhaifeng/articles/7806303.html'),
get_page('wiki.python.org',url='/moin/BeginnersGuide'),
get_page('www.baidu.com',),
] loop=asyncio.get_event_loop()
loop.run_until_complete(asyncio.gather(*tasks))
loop.close()
二 aiohttp模块
aiohttp.request:发送一个request请求
import asyncio
import aiohttp #pip3 install aiohttp @asyncio.coroutine
def get_page(url): #https:// www.baidu.com:80 /
print('GET:%s' %url)
response=yield from aiohttp.request('GET',url=url) data=yield from response.read() print('url:%s size:%s' %(url,len(data))) #http://www.cnblogs.com/linhaifeng/articles/7806303.html
#https://wiki.python.org/moin/BeginnersGuide
#https://www.baidu.com/ tasks=[
get_page('http://www.cnblogs.com/linhaifeng/articles/7806303.html'),
get_page('https://wiki.python.org/moin/BeginnersGuide'),
get_page('https://www.baidu.com/',),
] loop=asyncio.get_event_loop()
loop.run_until_complete(asyncio.gather(*tasks))
loop.close()
三 twisted模块
twisted:异步IO框架模块
getpage:发送请求
internet.reactor:
addCalllback:绑定回调函数
defer.DeferredList:
reactor.run:起循环来负责执行任务
addBoth:所有的任务都执行完毕过后执行的事,接收的参数是回调函数返回的结果
reactor.stop:终止程序的执行
'''
#问题一:error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools
https://www.lfd.uci.edu/~gohlke/pythonlibs/#twisted
pip3 install C:\Users\Administrator\Downloads\Twisted-17.9.0-cp36-cp36m-win_amd64.whl
pip3 install twisted #问题二:ModuleNotFoundError: No module named 'win32api'
https://sourceforge.net/projects/pywin32/files/pywin32/ #问题三:openssl
pip3 install pyopenssl
''' #twisted基本用法
from twisted.web.client import getPage,defer
from twisted.internet import reactor def all_done(arg):
# print(arg)
reactor.stop() def callback(res):
print(res)
return 1 defer_list=[]
urls=[
'http://www.baidu.com',
'http://www.bing.com',
'https://www.python.org',
]
for url in urls:
obj=getPage(url.encode('utf=-8'),)
obj.addCallback(callback)
defer_list.append(obj) defer.DeferredList(defer_list).addBoth(all_done) reactor.run() #twisted的getPage的详细用法
from twisted.internet import reactor
from twisted.web.client import getPage
import urllib.parse def one_done(arg):
print(arg)
reactor.stop() post_data = urllib.parse.urlencode({'check_data': 'adf'})
post_data = bytes(post_data, encoding='utf8')
headers = {b'Content-Type': b'application/x-www-form-urlencoded'}
response = getPage(bytes('http://dig.chouti.com/login', encoding='utf8'),
method=bytes('POST', encoding='utf8'),
postdata=post_data,
cookies={},
headers=headers)
response.addBoth(one_done) reactor.run()
四 trnado模块
from tornado.httpclient import AsyncHTTPClient
from tornado.httpclient import HTTPRequest
from tornado import ioloop def handle_response(response):
"""
处理返回值内容(需要维护计数器,来停止IO循环),调用 ioloop.IOLoop.current().stop()
:param response:
:return:
"""
if response.error:
print("Error:", response.error)
else:
print(response.body) def func():
url_list = [
'http://www.baidu.com',
'http://www.bing.com',
]
for url in url_list:
print(url)
http_client = AsyncHTTPClient()
http_client.fetch(HTTPRequest(url), handle_response) ioloop.IOLoop.current().add_callback(func)
ioloop.IOLoop.current().start()
爬虫模块之解决IO的更多相关文章
- 采集爬虫中,解决网站限制IP的问题? - wendi_0506的专栏 - 博客频道 - CSDN.NET
采集爬虫中,解决网站限制IP的问题? - wendi_0506的专栏 - 博客频道 - CSDN.NET undefined
- IIS发布网站浏览之后看到的是文件目录 & Internal Server Error 处理程序“ExtensionlessUrlHandler-ISAPI-4.0_64bit”在其模块列表中有一个错误模块“IsapiModule” 解决方法 & App_global.asax.pduxejp_.dll”--“拒绝访问。 ”
Q:IIS发布网站浏览之后看到的是文件目录 A:它出现了一个说到.NET4.0 更高框架什么的错误,所以我将 .NTE CRL版本由4.0改为2.0了,改为2.0后就出现了只能浏览文件目录了.改为4. ...
- 爬虫模块BeautifulSoup
中文文档:https://www.crummy.com/software/BeautifulSoup/bs4/doc/index.zh.html# 1.1 安装BeautifulSoup模块 ...
- [代码]--IIS发布网站浏览之后看到的是文件目录 & Internal Server Error 处理程序“ExtensionlessUrlHandler-ISAPI-4.0_64bit”在其模块列表中有一个错误模块“IsapiModule” 解决方法 & App_global.asax.pduxejp_.dll”--“拒绝访问。 ”
Q:IIS发布网站浏览之后看到的是文件目录 A:它出现了一个说到.NET4.0 更高框架什么的错误,所以我将 .NTE CRL版本由4.0改为2.0了,改为2.0后就出现了只能浏览文件目录了.改为4. ...
- 通过开启子进程的方式实现套接字服务端可以并发的处理多个链接以及通讯循环(用到了subprocess模块,解决粘包问题)
今日作业:通过开启子进程的方式实现套接字服务端可以并发的处理多个链接以及通讯循环(用到了subprocess模块,解决粘包问题) server(服务端) import socket from mult ...
- python爬虫---单线程+多任务的异步协程,selenium爬虫模块的使用
python爬虫---单线程+多任务的异步协程,selenium爬虫模块的使用 一丶单线程+多任务的异步协程 特殊函数 # 如果一个函数的定义被async修饰后,则该函数就是一个特殊的函数 async ...
- win10执行Tensorflow,总是会报错“DLL load failed: 找不到指定的模块”的解决方式----终极版方式
win10上运行tensorflow时报错,“DLL load failed: 找不到指定的模块”的解决方式 我只想说,当你们遇到这个问题的时候,以下终极版的方式出来了,非常感谢知乎 leo lv ! ...
- Java 使用正则表达式和IO实现爬虫以及503解决
我这边找了个小说网站: 基本套路: 第一步:获取小说每一章的url地址 第二步:获取章节url内容并使用正则表达式提取需要的内容 第三步:多线程封装,实现如下效果 最后测试. 代码: 内容获取封装: ...
- 爬虫模块介绍--request(发送请求模块)
爬虫:可见即可爬 # 每个网站都有爬虫协议 基础爬虫需要使用到的三个模块 requests 模块 # 模拟发请求的模块 PS:python原来有两个模块urllib和urllib的升级urlli ...
随机推荐
- 牛客网练习赛43-C(图论)
题目链接:https://ac.nowcoder.com/acm/contest/548/C 题意:有n个知识点,学会每个知识点花T[i],已经学会了其中k个知识点,有m组关系,t1,t2,t3,表示 ...
- WAS 常见报错
1) An error occurred while deleting the server. ADMG0011E: An unexpected exception occurred com.ibm. ...
- RxJS之BehaviorSubject
Subject 的其中一个变体就是 BehaviorSubject,它有一个“当前值”的概念.它保存了发送给消费者的最新值.并且当有新的观察者订阅时,会立即从 BehaviorSubject 那接收到 ...
- f5通过vs访问其他站点的源、目的IP问题
通过VIP访问其他站点,则事实上是从服务器访问到其他站点. 如,域名 a.xin.com解析到vip 10.16.100.47(member为10.16.45.71和10.16.45.72)访问192 ...
- 【c++】c++ 11之lamba表达式
C++ lambda表达式与函数对象 lambda表达式是C++11中引入的一项新技术,利用lambda表达式可以编写内嵌的匿名函数,用以替换独立函数或者函数对象,并且使代码更可读.但是从本质上来讲, ...
- java 基础之--java动态代理
1.抽象角色:声明真实对象与代理对象的共同接口: 2.代理角色:相当于中介的作用,bridge,内部包含对真实角色的reference,在执行真实操作对象时,附加其他操作,相当于对真实角色的封装: 3 ...
- java 基础之--传统网络编程
什么是socket ? socket 是连接运行在网络上的两个程序间的双向通讯端点 服务器将某一套接字绑定到一个特定的端口,并通过这一套接字等待和监听客户端的的连接请求 客户端通过这个端口与服务器进行 ...
- 我的第一个博客——Fragment遇到的问题
最近项目中使用fragment时遇到了一些问题: 1.fragment的刷新问题. 解决:我的情况是有多个fragment时,只需要刷新其中几个界面.之前我在网上看到的一些方法.如下: 首先在Adap ...
- python学习-类属性和实例属性
#类属性和实例属性 class Tool(object): #类属性 total = 0 #静态方法 @classmethod def say(self): print("hello wor ...
- [ERR] Node 192.168.25.135:7001 is not empty. Either the node already knows other nodes (check with CLUSTER NODES) or contains some key in database 0.
原文链接:https://www.cnblogs.com/huxinga/p/6644226.html 解决办法:将redis全部shutdown 将每个节点下aof.rdb.nodes.conf本地 ...