使用Python怎么实现一个多线程爬虫功能

发布时间:2020-12-18 14:19:34 作者:Leah
来源:亿速云 阅读:172

本篇文章为大家展示了使用Python怎么实现一个多线程爬虫功能,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

所用到得库

import os
import requests
from bs4 import BeautifulSoup

功能

# 多线程程序需要用到的一些包
# 队列
from queue import Queue
from threading import Thread

环境配置

解释器 python3.6
编辑器 pycharm专业版 激活码

多线程类代码

# 多线程类
class Download_Images(Thread):
  # 重写构造函数
  def __init__(self, queue, path):
    Thread.__init__(self)
    # 类属性
    self.queue = queue
    self.path = path
    if not os.path.exists(path):
      os.mkdir(path)
  def run(self) -> None:
    while True:
      # 图片资源的url链接地址
      url = self.queue.get()
      try:
        download_images(url, self.path)
      except:
        print('下载失败')
      finally:
        # 当爬虫程序执行完成/出错中断之后发送消息给线程 代表线程必须停止执行
        self.queue.task_done()

爬虫代码

# 爬虫代码
def download_images(url, path):
  headers = {
    'User-Agent':
      'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36'
  }
  response = requests.get(url, headers=headers)
  soup = BeautifulSoup(response.text, 'lxml')
  img_list = soup.find_all('img', class_='ui image lazy')
  for img in img_list:
    image_title = img['title']
    image_url = img['data-original']

    try:
      with open(path + image_title + os.path.splitext(image_url)[-1], 'wb') as f:
        image = requests.get(image_url, headers=headers).content
        print('正在保存图片:', image_title)
        f.write(image)
        print('保存成功:', image_title)
    except:
      pass

if __name__ == '__main__':
  _url = 'https://fabiaoqing.com/biaoqing/lists/page/{page}.html'
  urls = [_url.format(page=page) for page in range(1, 201)]
  queue = Queue()
  path = './threading_images/'
  for x in range(10):
    worker = Download_Images(queue, path)
    worker.daemon = True
    worker.start()
  for url in urls:
    queue.put(url)
  queue.join()
  print('下载完成...')

上述内容就是使用Python怎么实现一个多线程爬虫功能,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。

推荐阅读:
  1. PHP怎样使用swoole实现多线程爬虫?
  2. Python使用队列方式实现多线程爬虫的方法

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python 多线程 多线程爬

上一篇:linux下如何查看redis的安装目录

下一篇:怎么在中springcloud中对pom.xml进行配置

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》