(11).scrapy依赖的模块Twisted
时间:2022-05-05 17:58
#!/usr/bin/env python # -*- coding:utf-8 -*- # author:love_cat from twisted.internet import reactor # 事件循环(终止条件,所有的socket都已经移除) from twisted.internet import defer # defer.Deferred 特殊的socket对象(不发请求,手动移除) from twisted.web.client import getPage # 用于创建socket对象(下载完成,自动从事件循环中移除) # 1. 利用getPage创建socket # 2. 将socket添加到事件循环 # 3. 开始事件循环(内部发送请求,并接受响应;当所有的socket完成后,终止事件循环) def response(content): print(content.decode(‘utf-8‘)) @defer.inlineCallbacks def task(): url = ‘http://www.bilibili.com‘ d = getPage(url.encode(‘utf-8‘)) # 加上装饰器,得到特殊的socket对象。不发请求,只待在事件循环里面,用于让事件循环一直持续,直到我们手动移除 d.addCallback(response) yield d task() reactor.run() # 程序的输出结果如下 ‘‘‘哔哩哔哩 (゜-゜)つロ 干杯~-bilibili ‘‘‘ @defer.inlineCallbacks def task1(): url = ‘http://www.bilibili.com‘ d = getPage(url.encode(‘utf-8‘)) d.addCallback(response) yield d @defer.inlineCallbacks def task2(): url=‘http://www.baidu.com‘ d = getPage(url.encode(‘utf-8‘)) d.addCallback(response) url = ‘http://www.bilibili.com‘ d = getPage(url.encode(‘utf-8‘)) d.addCallback(response) yield d def response(content): print(content.decode(‘utf-8‘)[0:1000]) # 这里只取前1000个字符 def run_until_complete(*args,**kwargs): reactor.stop() t1 = task1() t2 = task2() all_task = defer.DeferredList([t1,t2]) all_task.addBoth(run_until_complete) reactor.run() # 程序的输出结果如下 ‘‘‘正在加载...正在加载...哔哩哔哩 (゜-゜)つロ 干杯~-bilibili 哔哩哔哩 (゜-゜)つロ 干杯~-bilibili #!/usr/bin/env python # -*- coding:utf-8 -*- # author:love_cat from twisted.internet import reactor,task def hello(name): print(‘hello‘, name) task1 = task.LoopingCall(hello, ‘satori‘) # 每隔十秒钟运行一次 task1.start(10) reactor.callWhenRunning(hello, ‘mmp‘) # 当循环开始时,运行 reactor.callLater(3, hello, ‘mmppp‘) # 循环开始后三秒,运行 reactor.run() ‘‘‘ hello satori hello mmp hello mmppp hello satori hello satori hello satori hello satori hello satori ..... ..... ..... ‘‘‘