Python多线程爬取网站图片

本文介绍了一种利用Python多线程技术优化网络资源下载效率的方法,通过并行下载避免了单线程爬虫可能遇到的阻塞问题,提高了爬虫的稳定性和速度。文章详细展示了如何使用Python的threading模块创建和管理线程,以及如何使用线程锁确保数据的安全写入。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

多线程执行爬虫避免某个网络资源卡住其他资源下载;

Python线程相关知识点:

  1. import threading  引入线程
  2. t = Thread(target,args=None)   定义一个线程
  3. t.start() 线程开始
  4. t.setDaemon(False) 默认 设置线程后台模式运行;
  5. t.setDaemon(True) 设置线程前台模式运行;
  6. t.join (当前程序)等待线程t执行完毕;
  7. lock=threading.RLOCK() 创建线程锁对象
  8. lock.acquire() 强迫lock获取线程锁,如果被占用则等待
  9. lock.release() 释放锁


from bs4 import BeautifulSoup
from bs4 import UnicodeDammit
import urllib.request
import threading

def imageSpider(start_url):
    global threads
    global count
    try:
        urls=[]
        req=urllib.request.Request(start_url,headers=headers)
        data = urllib.request.urlopen(req)
        data=data.read()
        dammit=UnicodeDammit(data,["utf-8","gbk"])
        data=dammit.unicode_markup
        soup=BeautifulSoup(data,"html.parser")
        images=soup.select("img")
        print (images)
        for image in images:
            try:
                src=image["src"]
                url = urllib.request.urljoin(start_url,src)
                if url not in urls:
                    urls.append(url)
                    print (url)
                    count=count+1
                    T=threading.Thread(target=download,args=(url,count))
                    T.setDaemon(False)
                    T.start()
                    threads.append(T)
            except Exception as err:
                print (err)
    except Exception as err:
        print (err)

def download(url,count):
    try:
        if(url[len(url)-4]=="."):
            ext=url[len(url)-4:]
        else:
            ext=".jpg"
        req=urllib.request.Request(url,headers=headers)
        data = urllib.request.urlopen(req,timeout=100)
        data=data.read()
        fobj=open("images\\"+str(count)+ext,"wb")
        fobj.write(data)
        fobj.close()
        print ("downloaded"+str(count)+ext)
    except Exception as err:
        print (err)


start_url="https://www.youkuaiyun.com/"
headers={"User-Agent": "Mozilla/5.0 (Windows; U; Windows NT 6.0 x64; en-US; rv:1.9pre) Gecko/2008072421 Minefield/3.0.2pre"}
count=0
threads=[]
imageSpider(start_url)
for t in threads:
    t.join()
print("the End")

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值