Python爬虫多线程

Python中使用线程有两种方式:函数或者用类来包装线程对象。

Python 2 可以使用thread方法,我用的是Python 3 ,使用threading方法

使用Threading模块创建线程,直接从threading.Thread继承,然后重写__init__方法和run方法:

代码示例:

#导入模块
import threading
import time
import requests

#定义方法func1
def func1():

    #设定开始时间
    time_start = time.time()

    #用requests方法爬取百度信息
    r = requests.get(url='http://www.baidu.com')

    #获得爬取时间
    times = time.time()-time_start

    #打印状态码和爬取时间
    print('Status:%s--%s--%s\n'%(r.status_code,times,time.strftime('%H:%M:%S')))

def main():

    threads = []

    #设置线程数
    threads_count = 10
    for i in range(threads_count):
        t = threading.Thread(target=func1,args={})
        threads.append(t)
    for i in range(threads_count):
        threads[i].start()
    for i in range(threads_count):
        threads[i].join()

if __name__ == '__main__':
    main()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值