1 #!/usr/bin/env python
2 # -- coding:utf-8 --
3 # asyncio 没有提供http协议的接口
4 import asyncio
5 import time
6 from urllib.parse import urlparse
7
8
9 async def get_url(url):
10 url = urlparse(url)
11 host = url.netloc
12 path = url.path
13 if path == '':
14 path = '/'
15
16 # 建立连接
17 # asyncio.open_connection是一个协程
18 reader, writer = await asyncio.open_connection(host, 80)
19 writer.write("GET {} HTTP/1.1\r\nHost:{}\r\nConnection:close\r\n\r\n".format(path, host).encode('utf-8'))
20 all_lines = 【】
21 async for raw_line in reader:
22 line = raw_line.decode('utf-8')
23 all_lines.append(line)
24 html = '\n'.join(all_lines)
25 return html
26
27
28 async def main():
29 tasks = 【】
30 for url in range(1, 21):
31 url = ''.format(url)
32 tasks.append(asyncio.ensure_future(get_url(url)))
33 for task in asyncio.as_completed(tasks):
34 # asyncio.as_completed返回的是一个协程
35 result = await task
36 //代码效果参考:http://www.zidongmutanji.com/zsjx/353591.html print(result)
37
38
39 if name == 'main':
40 start_time = time.time()
41 loop = asyncio.get_event_loop()
42 loop.run_until_complete(main())
43 print('last time:{}'.format(time.time() - start_time))
?123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421HTTP/1.1 200 OK Server: nginx/1.12.2 Date: Mon, 19 Aug 2019 11:38:06 GMT Content-Type: application/json Content-Length: 1497 Connection: close Vary: Accept, Cookie Allow: GET, HEAD, OPTIONS X-Frame-Options: SAMEORIGIN {"id":1,"category":{"id":129,"sub_cat":【】,"name":"根茎类","code":"gjl","desc":"","category_type":2,"is_tab