37,719
社区成员
发帖
与我相关
我的任务
分享
from concurrent.futures import ThreadPoolExecutor
import requests
urls = ['http://httpbin.org'] * 16
threadpool = ThreadPoolExecutor(max_workers=4)
def get_webpage(url):
r = requests.get(url)
print(r)
return r
for url in urls:
threadpool.submit(get_webpage, url)
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib.request
import time
from threading import Thread
class ThreadWithResult(Thread):
def __init__(self, func, args=()):
super(ThreadWithResult, self).__init__()
self.func = func
self.args = args
self.result = None
def run(self):
self.result = self.func(*self.args)
def get_result(self):
return self.result
def getHtml(url):
try:
print(url)
page = urllib.request.urlopen(url, timeout=10)
html = page.read()
print(html) # 处理一些事情
except Exception:
pass
single_result = 1 # 前面的结果
return single_result
def main(key1, key2):
print(key1)
print(key2)
total_return = 0
ls_site = ["www.1.com", "www.2.com", "www.3.com", "www.4.com"]
time_string = time.strftime("%Y%m%d%H%M%S")
threads = []
for site in ls_site:
url = "http://{}/?{}".format(site, time_string)
t = ThreadWithResult(func=getHtml, args=(url,))
t.start()
threads.append(t)
for t in threads:
t.join()
total_return += t.get_result()
print(total_return)
if __name__ == '__main__':
main('key1', 'key2')