文章目录

  • 一、带有返回值的多线程
    • 1.1 实现代码
    • 1.2 结果
  • 二、实现过程
    • 2.1 一个普通的单线程爬虫函数
    • 2.2 一个简单的多线程传值实例
    • 2.3 实现重点
  • 三、代码实战
  • 四、学习

一、带有返回值的多线程

1.1 实现代码

# -*- coding:utf-8 -*-
"""
作者:wyt
日期:2022年04月21日
"""import threading
import requests
import timeurls = [f'https://www.cnblogs.com/#p{page}' # 待爬地址for page in range(1, 10)  # 爬取1-10页
]def craw(url):r = requests.get(url)num = len(r.text)  # 爬取博客园当页的文字数return num  # 返回当页文字数def sigle():  # 单线程res = []for i in urls:res.append(craw(i))return resclass MyThread(threading.Thread):  # 重写threading.Thread类,加入获取返回值的函数def __init__(self, url):threading.Thread.__init__(self)self.url = url                # 初始化传入的urldef run(self):                    # 新加入的函数,该函数目的:self.result = craw(self.url)  # ①。调craw(arg)函数,并将初试化的url以参数传递——实现爬虫功能# ②。并获取craw(arg)函数的返回值存入本类的定义的值result中def get_result(self):  #新加入函数,该函数目的:返回run()函数得到的resultreturn self.resultdef multi_thread():print("start")threads = []           # 定义一个线程组for url in urls:threads.append(    # 线程组中加入赋值后的MyThread类MyThread(url)  # 将每一个url传到重写的MyThread类中)for thread in threads: # 每个线程组startthread.start()for thread in threads: # 每个线程组jointhread.join()list = []for thread in threads:list.append(thread.get_result())  # 每个线程返回结果(result)加入列表中print("end")return list  # 返回多线程返回的结果组成的列表if __name__ == '__main__':start_time = time.time()result_multi = multi_thread()print(result_multi)  # 输出返回值-列表# result_sig = sigle()# print(result_sig)end_time = time.time()print('用时:', end_time - start_time)

1.2 结果

单线程:

多线程:

加速效果明显。

二、实现过程

2.1 一个普通的单线程爬虫函数

import threading
import requests
import timeurls = [f'https://www.cnblogs.com/#p{page}' # 待爬地址for page in range(1, 10)  # 爬取1-10页
]def craw(url):r = requests.get(url)num = len(r.text)  # 爬取博客园当页的文字数print(num)def sigle():  # 单线程res = []for i in urls:res.append(craw(i))return resif __name__ == '__main__':start_time = time.time()result_sig = sigle()print(result_sig)end_time = time.time()print('用时:', end_time - start_time)

2.2 一个简单的多线程传值实例

import timefrom threading import Threaddef foo(number):time.sleep(1)return numberclass MyThread(Thread):def __init__(self, number):Thread.__init__(self)self.number = numberdef run(self):self.result = foo(self.number)def get_result(self):return self.resultif __name__ == '__main__':thd1 = MyThread(3)thd2 = MyThread(5)thd1.start()thd2.start()thd1.join()thd2.join()print(thd1.get_result())print(thd2.get_result())

返回:

3
5

2.3 实现重点

  1. 多线程入口

    threading.Thread(target=craw,args=(url,)) # 注意args=(url,),元组

  2. 多线程传参
    需要重写一下threading.Thread类,加一个接收返回值的函数。

三、代码实战

使用这种带返回值的多线程技术重写了一下之前发布过的一个爬取子域名的代码,原始代码在这里:https://blog.csdn.net/qq_45859826/article/details/124030119

import threadingimport requests
from bs4 import BeautifulSoup
from static.plugs.headers import get_ua#https://cn.bing.com/search?q=site%3Abaidu.com&go=Search&qs=ds&first=20&FORM=PEREdef search_1(url):Subdomain = []html = requests.get(url, stream=True, headers=get_ua())soup = BeautifulSoup(html.content, 'html.parser')job_bt = soup.findAll('h2')for i in job_bt:link = i.a.get('href')# print(link)if link not in Subdomain:Subdomain.append(link)return Subdomainclass MyThread(threading.Thread):def __init__(self, url):threading.Thread.__init__(self)self.url = urldef run(self):self.result = search_1(self.url)def get_result(self):return self.resultdef Bing_multi_thread(site):print("start")threads = []for i in range(1, 30):url = "https://cn.bing.com/search?q=site%3A" + site + "&go=Search&qs=ds&first=" + str((int(i) - 1) * 10) + "&FORM=PERE"threads.append(MyThread(url))for thread in threads:thread.start()for thread in threads:thread.join()res_list = []for thread in threads:res_list.extend(thread.get_result())res_list = list(set(res_list)) #列表去重number = 1for i in res_list:number += 1number_list = list(range(1, number + 1))dict_res = dict(zip(number_list, res_list))print("end")return dict_resif __name__ == '__main__':print(Bing_multi_thread("qq.com"))

返回:

{
1:'https://transmart.qq.com/index',
2:'https://wpa.qq.com/msgrd?v=3&uin=448388692&site=qq&menu=yes',
3:'https://en.exmail.qq.com/',
4:'https://jiazhang.qq.com/wap/com/v1/dist/unbind_login_qq.shtml?source=h5_wx',
5:'http://imgcache.qq.com/',
6:'https://new.qq.com/rain/a/20220109A040B600',
7:'http://cp.music.qq.com/index.html',
8:'http://s.syzs.qq.com/',
9:'https://new.qq.com/rain/a/20220321A0CF1X00',
10:'https://join.qq.com/about.html',
11:'https://live.qq.com/10016675',
12:'http://uni.mp.qq.com/',
13:'https://new.qq.com/omn/TWF20220/TWF2022042400147500.html',
14:'https://wj.qq.com/?from=exur#!',
15:'https://wj.qq.com/answer_group.html',
16:'https://view.inews.qq.com/a/20220330A00HTS00',
17:'https://browser.qq.com/mac/en/index.html',
18:'https://windows.weixin.qq.com/?lang=en_US',
19:'https://cc.v.qq.com/upload',
20:'https://xiaowei.weixin.qq.com/skill',
21:'http://wpa.qq.com/msgrd?v=3&uin=286771835&site=qq&menu=yes',
22:'http://huifu.qq.com/',
23:'https://uni.weixiao.qq.com/',
24:'http://join.qq.com/',
25:'https://cqtx.qq.com/',
26:'http://id.qq.com/',
27:'http://m.qq.com/',
28:'https://jq.qq.com/?_wv=1027&k=pevCjRtJ',
29:'https://v.qq.com/x/page/z0678c3ys6i.html',
30:'https://live.qq.com/10018921',
31:'https://m.campus.qq.com/manage/manage.html',
32:'https://101.qq.com/',
33:'https://new.qq.com/rain/a/20211012A0A3L000',
34:'https://live.qq.com/10021593',
35:'https://pc.weixin.qq.com/?t=win_weixin&lang=en',
36:'https://sports.qq.com/lottery/09fucai/cqssc.htm'
}

非常非常非常能感受到速度快了超级多,用这种方式爆破子域名也比较爽。没有多线程,我的项目里可能缺少了好几个功能:因为之前写过的一些程序都因执行时间过长被我砍掉。这个功能还是很实用的。


四、学习

B站python-多线程教程:https://www.bilibili.com/video/BV1bK411A7tV

2022年4月28日于家中,加油!

先自我介绍一下,小编13年上师交大毕业,曾经在小公司待过,去过华为OPPO等大厂,18年进入阿里,直到现在。深知大多数初中级java工程师,想要升技能,往往是需要自己摸索成长或是报班学习,但对于培训机构动则近万元的学费,着实压力不小。自己不成体系的自学效率很低又漫长,而且容易碰到天花板技术停止不前。因此我收集了一份《java开发全套学习资料》送给大家,初衷也很简单,就是希望帮助到想自学又不知道该从何学起的朋友,同时减轻大家的负担。添加下方名片,即可获取全套学习资料哦

【python】python实现多线程并得到返回值相关推荐

  1. Python基本语法_函数_返回值

    目录 目录 前言 函数的返回值 在函数中Return和Print的区别 函数中的文档 前言 函数的返回值是函数重要的组成部分.函数的根本在于实现程序的部分功能,所以很多时候我们需要将函数执行后的结果返 ...

  2. Python深度学习实战:声呐返回值分类

    Python深度学习实战:声呐返回值分类 声呐物体分类数据 简单的神经网络 预处理数据以增加性能 调整模型的拓扑和神经元 缩小网络 扩大网络 总结 本章我们使用Keras开发一个二分类网络.本章包括: ...

  3. python CV2中shape和resize返回值和参数的区别

    python CV2中shape和resize返回值和参数的区别 1.在一副图像中使用shape得到一个3个类别的列表 shape[0] =图像的高 shape[1] =图像的宽 shape[2] = ...

  4. BeginInvoke与EndInvoke方法解决多线程接收委托返回值问题

    BeginInvoke与EndInvoke方法解决多线程接收委托返回值问题 参考文章: (1)BeginInvoke与EndInvoke方法解决多线程接收委托返回值问题 (2)https://www. ...

  5. python限定方法参数类型、返回值类型、变量类型

    typing模块的作用 自python3.5开始,PEP484为python引入了类型注解(type hints) 类型检查,防止运行时出现参数和返回值类型.变量类型不符合. 作为开发文档附加说明,方 ...

  6. python限定方法参数类型、返回值类型、变量类型等

    typing模块的作用 自python3.5开始,PEP484为python引入了类型注解(type hints) 类型检查,防止运行时出现参数和返回值类型.变量类型不符合. 作为开发文档附加说明,方 ...

  7. python函数定义参数类型和返回值类型

    python中我们也可以定义函数的参数类型和返回值类型,如下代码 #函数参数和返回值的类型声明,python函数类型的声明,更加有意义,更加实用一些 def add(a,b):''':param a: ...

  8. Python教程:函数多个返回值与丢弃返回值

    1.函数多个返回值 python的函数支持返回多个值.返回多个值时,默认以tuple的方式返回. 例如,下面两个函数的定义是完全等价的. def f():return 1,2def f():retur ...

  9. Python技术手册 · 函数的多返回值&文件操作

    目录 ​函数的多返回值&文件操作 ​函数的多返回值 ​多返回值返回方式 ​函数的传参方式(以不同的使用方式分类) 位置参数 关键字参数 缺省参数 不定长参数 ​匿名函数(lambda) ​函数 ...

  10. python os system_python中os.system返回值为-1是什么意思?

    其实这是一个比较复杂的问题. 你是通过 os.system() 这个函数来获得的返回值,那么其内部调用的是通过 C++/C 写的和操作系统交互的 Python 底层代码.这里你没有说明你的操作系统是 ...

最新文章

  1. R语言使用ggplot2包的快速可视化函数qplot绘制分组点图(带状图)并配置分组颜色实战
  2. OpenStack遇到的坑
  3. C++(Goto使用实例)
  4. java 优先队列从小到大,优先队列(Java)
  5. AI到底有多吃香?推荐一个斯坦福、CMU、清北学生都在上的AI课
  6. QT简介及QT环境搭建
  7. PHP方向+go+rpc+swoole,瞅瞅 PHP+Swoole 作为网络通信框架
  8. python 网格_Python | 网格到情节
  9. Bootstrap表单的可选布局
  10. ES6_let和const_note
  11. centeros下安装python
  12. while 循环判断时 遇到赋值表达式
  13. python 连接 mysql
  14. 两个苹果手机共享步数_最新刷步教程 | 蚂蚁森林如何快速刷步数,获得296g能量...
  15. c libxml2库的编译和使用
  16. 【Android】局域网屏幕共享与反向控制功能的实现
  17. 万字详解 GoF 23 种设计模式(多图、思维导图、模式对比),让你一文全面理解
  18. 利用python更改图片格式和分辨率
  19. 色纯度(purity)主波长(WD)计算软件
  20. KOD: Linux 命令行安装

热门文章

  1. mq 的Publish/Subscribe 模式
  2. 计算机关闭账号用户控制好吗,Win10系统彻底关闭用户帐户控制的方法
  3. iphone 越狱需要安装的包
  4. 看到这些网络骗局信息,请千万留个心眼
  5. oracle list分区添加,oracle 11g 如何创建、修改、删除list-list组合分区
  6. 百利药业IPO过会:扣非后年亏1.5亿 奥博资本是股东
  7. 架构漫谈专栏系列文章
  8. win10系统设置番茄家园开机音乐以及关机音乐(亲测有效)
  9. macos 获取root权限
  10. 这个母亲节,带妈妈一起学习网络防骗术