首页 > 编程语言 >1、使用python+selenium+requests在百度批量下载图片

1、使用python+selenium+requests在百度批量下载图片

时间:2023-07-20 20:26:40浏览次数:66  
标签:__ img python selenium self driver 滚动条 time requests

import os
import re
import time
import requests
from selenium import webdriver
from selenium.webdriver.common.by import By


class picturesDowload():
  def __init__(self, insearch, savepath=os.path.dirname(__file__), timeout=10):
    self.insearch = insearch     self.picspath = savepath
    self.options = webdriver.ChromeOptions()
    self.options.add_argument('headless') # 设置不打开浏览器
    self.driver = webdriver.Chrome(options=self.options)
    self.driver.implicitly_wait(5)

  def loadPage(self):
    self.driver.get('https://www.baidu.com/')
    self.driver.find_element(By.LINK_TEXT, '图片').click() # 点击【图片】文本链接
    try:
      self.driver.switch_to.window(self.driver.window_handles[1]) # 切换句柄
    except:
      pass
    self.driver.find_element(By.ID, 'kw').send_keys(self.insearch) # 输入搜索的关键字
    self.driver.find_element(By.XPATH, '//*[@id="homeSearchForm"]/span[2]/input').click() # 执行搜索
    js = "return action=document.body.scrollHeight"
    height = self.driver.execute_script(js) # 获取滚动条高度
    self.driver.execute_script('window.scrollTo(0, document.body.scrollHeight)') # 将滚动条拖至底部
    t1 = int(time.time()) # 初始时间戳
    num = 1
    while True:
      t2 = int(time.time())
      if t2 - t1 < 10: # 判断初始时间戳和当前时间戳差值,小于10秒则下拉滚动条
        new_height = self.driver.execute_script(js)
        if new_height > height:
          self.driver.execute_script('window.scrollTo(0, document.body.scrollHeight)') # 将滚动条拖至底部
          height = new_height # 重置滚动条高度数值
          t1 = int(time.time()) # 重置时间戳
      elif num < 4: # 当超过10秒页面高度仍然没有更新时,进入重试逻辑,重试3次,每次等待3秒
        print('下拉滚动条,第%d次重试' % num)
        time.sleep(3)
        self.driver.execute_script('window.scrollTo(0, document.body.scrollHeight)') # 将滚动条拖至底部
        t1 = int(time.time()) # 重置时间戳
        num = num + 1
      else:
        print("重试结束,当前页面数据已加载完毕!")
        self.driver.execute_script('window.scrollTo(0, 0)') # 滚动条调整至页面顶部
        break

  def dowload(self):
    self.picsPath = os.path.join(self.picspath, self.insearch)
    if not os.path.exists(self.picsPath):
      os.makedirs(self.picsPath)
    self.loadPage()
    img_urls = re.findall(r'src="https://img\S+', self.driver.page_source) # 搜索页面中所有满足条件的图片链接
    print('本次搜索到图片%d张' % len(img_urls))
    for num, url in enumerate(img_urls): # 获取图片url
      url = url.split('"')[1]
      img_urls[num] = url

    t3 = int(time.time())
    for key, url in enumerate(img_urls):
      res = requests.get(url)
      with open(r"%s\%d.png" % (self.picsPath, key), 'wb') as f:
        f.write(res.content)
      t4 = int(time.time())
      if key == len(img_urls) - 1:
        print('已下载完成进度100%')
      elif t4 - t3 > 5:
        print('已下载完成进度 {0}%'.format(int(key / len(img_urls) * 100)))
        t3 = int(time.time())

if __name__ == '__main__':
  obj = picturesDowload('刘亦菲')
  obj.dowload()

标签:__,img,python,selenium,self,driver,滚动条,time,requests
From: https://www.cnblogs.com/moming-Zhong/p/17569559.html

相关文章

  • [oeasy]python0073_进制转化_eval_evaluate_衡量_oct_octal_八进制
    进制转化回忆上次内容上次了解的是整型数字类变量integer前缀为i ​ 添加图片注释,不超过140字(可选) 整型变量和字符串变量不同整型变量是直接存储二进制形式的可以用int()函数将2进制形式的字符串转化为......
  • python监控redis主从 双主 VIP切换
    [MySQL]master_host=master_port=3306master_user=rootmaster_password=slave_host=[DingTalk]#生产prod_webhook_url=https://oapi.dingtalk.com/robot/send?access_token=prod_secret=#测试dev_webhook_url=https://oapi.dingtalk.com/robot/send?access_tok......
  • Python监控Nginx 4、7层健康检查
    [root@acs-hk-ctos7-prod-01scripts]#catupstrem.py#!/usr/bin/envpython#-*-coding:utf-8-*-#@Time:2023/6/2517:18#@File:nginx_upstram.py#@Software:PyCharmimportrequestsfromurllib.requestimporturlopenimportos,socket,datetim......
  • Python基础day49
    overflow溢出属性值描述visible默认值。内容不会被修剪,会呈现在元素框之外hidden内容会被修剪,并且其余内容是不可见的scroll内容会被修剪,但是浏览器会显示滚动条以便查看其余的内容auto如果内容被修剪,则浏览器会显示滚动条以便查看其余的内容inherit规定......
  • PYTHON 没有实体类做修改
    PYTHON没有实体类做修改在Python中,我们经常需要对数据进行操作和修改。有时候,我们可能需要修改一个已经存在的数据对象,或者需要创建一个新的数据对象来存储修改后的数据。在其他编程语言中,通常会使用实体类来实现这些操作。实体类是一个包含属性和方法的数据结构,可以用来表示现实......
  • Linux python 查找模块和版本号
    LinuxPython查找模块和版本号作为一名经验丰富的开发者,你需要教会一位刚入行的小白如何在Linux环境下使用Python查找模块和版本号。以下是一份详细的步骤和相应的代码注释,帮助他完成这个任务。步骤步骤描述步骤一打开终端步骤二运行Python交互式解释器步骤三......
  • Python字典换行
    Python字典换行的实现作为一名经验丰富的开发者,我将教会你如何实现Python字典换行。在本文中,我将详细介绍整个过程,并提供每一步所需的代码和代码注释。流程概述实现Python字典换行的过程可以分为以下几个步骤:创建一个字典。将字典的键值对分为多行。编写代码实现字典换行。......
  • VM虚拟机配置python环境
    如何配置Python环境的虚拟机引言在软件开发中,配置适当的开发环境是非常重要的。Python作为一种常用的编程语言,为了更好地管理项目和依赖,我们经常使用虚拟机来创建独立的Python环境。本文将为刚入行的开发者介绍如何配置Python环境的虚拟机。整体流程下面的表格展示了配置Python......
  • Python字典编码
    Python字典编码的实现介绍在Python中,字典是一种非常重要和常用的数据结构。字典可以存储键值对的数据,通过键来快速访问和修改对应的值。字典编码是将一个字典转换为字符串的过程,这样可以方便地将字典存储到文件中或者传输给其他系统。本文将介绍Python字典编码的实现步骤以及具......
  • Python中字符串可以直接用大于号小于号吗
    Python中字符串可以直接用大于号小于号吗在Python中,字符串是一种不可变的数据类型。我们可以使用双引号或单引号来定义字符串,比如"HelloWorld"或'Pythonisawesome'。字符串在Python中非常常用,因为它们可以包含文本和字符数据。但是,对于字符串来说,我们不能直接使用大于号(>)和小......