python 爬虫 线程池


test.html代码:
<html lang="en"> <head> <meta charset="UTF-8" /> <title>测试bs4</title> </head> <body> <div> <p>百里守约</p> </div> <div class="song"> <p>李清照</p> <p>王安石</p> <p>苏轼</p> <p>柳宗元</p> <a href="http://www.song.com/" title="赵匡胤" target="_self"> <span>this is span</span> 宋朝是最强大的王朝,不是军队的强大,而是经济很强大,国民都很有钱</a> <a href="" class="du">总为浮云能蔽日,长安不见使人愁</a> <img src="http://www.baidu.com/meinv.jpg" alt="" /> </div> <div class="tang"> <ul> <li><a href="http://www.baidu.com" title="qing">清明时节雨纷纷,路上行人欲断魂,借问酒家何处有,牧童遥指杏花村</a></li> <li><a href="http://www.163.com" title="qin">秦时明月汉时关,万里长征人未还,但使龙城飞将在,不教胡马度阴山</a></li> <li><a href="http://www.126.com" alt="qi">岐王宅里寻常见,崔九堂前几度闻,正是江南好风景,落花时节又逢君</a></li> <li><a href="http://www.sina.com" class="du">杜甫</a></li> <li><a href="http://www.dudu.com" class="du">杜牧</a></li> <li><b>杜小月</b></li> <li><i>度蜜月</i></li> <li><a href="http://www.haha.com" id="feng">凤凰台上凤凰游,凤去台空江自流,吴宫花草埋幽径,晋代衣冠成古丘</a></li> </ul> </div> </body> </html>
线程池代码:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import requests
import time
from multiprocessing.dummy import Pool
urls = [
'http://127.0.0.1:5000/bobo',
'http://127.0.0.1:5000/jay',
'http://127.0.0.1:5000/tom'
]
def get_request(url):
page_text = requests.get(url=url).text
return len(page_text)
#同步代码
# if __name__ == "__main__":
# start = time.time()
#
# for url in urls:
# res = get_request(url)
# print(res)
# print('总耗时:',time.time()-start)
#异步代码
if __name__ == "__main__":
start = time.time()
pool = Pool(3) #3表示开启线程的数量
#使用get_request作为回调函数,需要基于异步的形式对urls列表中的每一个列表元素进行操作
#保证回调函数必须要有一个参数和返回值
result_list = pool.map(get_request,urls)
print(result_list)
print('总耗时:', time.time() - start)
FlaskServer.py代码:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from flask import Flask,render_template
from time import sleep
#实例化一个app
app = Flask(__name__)
#创建视图函数&路由地址
@app.route('/bobo')
def index_1():
sleep(2)
return render_template('test.html')
@app.route('/jay')
def index_2():
sleep(2)
return render_template('test.html')
@app.route('/tom')
def index_3():
sleep(2)
return render_template('test.html')
if __name__ == "__main__":
#debug=True表示开启调试模式:服务器端代码被修改后按下保存键会自动重启服务
app.run(debug=True)
作者:龙飞
-------------------------------------------
个性签名:独学而无友,则孤陋而寡闻。做一个灵魂有趣的人!
如果觉得这篇文章对你有小小的帮助的话,记得在右下角点个“推荐”哦,博主在此感谢!
浙公网安备 33010602011771号