加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 创业 > C语言 > 正文

asyncio+ThreadPoolExecutor爬虫

发布时间:2020-12-15 01:23:47 所属栏目:C语言 来源:网络整理
导读:#使用多线程:在携程中集成阻塞ioimport asynciofrom concurrent.futures import ThreadPoolExecutorimport socketfrom urllib.parse import urlparse??def get_url(url):? ? #通过socket请求html? ? url = urlparse(url)? ? host = url.netloc? ? path = ur
#使用多线程:在携程中集成阻塞io
import asyncio
from concurrent.futures import ThreadPoolExecutor
import socket
from urllib.parse import urlparse
?
?
def get_url(url):
? ? #通过socket请求html
? ? url = urlparse(url)
? ? host = url.netloc
? ? path = url.path
? ? if path == "":
? ? ? ? path = "/"
?
? ? #建立socket连接
? ? client = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
? ? # client.setblocking(False)
? ? client.connect((host,80)) #阻塞不会消耗cpu
?
? ? #不停的询问连接是否建立好, 需要while循环不停的去检查状态
? ? #做计算任务或者再次发起其他的连接请求
?
? ? client.send("GET {} HTTP/1.1rnHost:{}rnConnection:closernrn".format(path,host).encode("utf8"))
?
? ? data = b""
? ? while True:
? ? ? ? d = client.recv(1024)
? ? ? ? if d:
? ? ? ? ? ? data += d
? ? ? ? else:
? ? ? ? ? ? break
?
? ? data = data.decode("utf8")
? ? html_data = data.split("rnrn")[1]
? ? print(html_data)
? ? client.close()
?
?
if __name__ == "__main__":
? ? import time
? ? start_time = time.time()
? ? loop = asyncio.get_event_loop()
? ? executor = ThreadPoolExecutor(10)
? ? tasks = []
? ? for url in range(20):
? ? ? ? url = "http://shop.projectsedu.com/goods/{}/".format(url)
? ? ? ? task = loop.run_in_executor(executor,get_url,url)
? ? ? ? tasks.append(task)
? ? loop.run_until_complete(asyncio.wait(tasks))
? ? print("last time:{}".format(time.time()-start_time))

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读