python http请求及多线程应用

目录

概述

  • 今天, 使用python3 模拟下发包, http get 请求, 然后 采用tomorrow 多线程.

代码如下:

# coding=utf-8
from urllib import request
import json
from tomorrow import threads
import time


@threads(100)
def testgetHtml(url):
    requests = request.urlopen(url)
    return requests


start = time.time()
url = "https://www.baidu.com/"
print('begin')

responses = [testgetHtml(url) for i in range(100)]
# html = [(json.loads(response.read().decode('utf-8')))['total'] 
html = [response.read().decode('utf-8') for response in responses]
for x in html:
    print(x)

tomorrow包准备

pip install tomorrow

运行环境遇到的问题

  • 移动python目录后, pip 默认安装路径与实际项目不匹配. 现象来说就是: cd 进入项目目录后运行如上安装命令是成功的, 但是运行python程序依然找不到tomorrow包, 开始怀疑默认pip路径安装问题. 解决方法步骤如下:
    • 更改了path系统环境, 修改python 及 python\scripts 的路径, 不生效, 错误依旧.
    • 重新安装pip. 方法: pip 官网下载后, 解压.tar.gz的格式, 然后 python setup.py install 安装成功, 错误消失

其他尝试未果

  • 尝试一个方法内完成Request 和 response 读取显示.: 各种报错, 未继续.
    • 可能的原因: 涉及异步过程, 无法合理追踪, 与预期的多线程有出入.