批量改文件名与爬虫

批量该文件名:

import os

path = input('请输入文件路径(结尾加上/):')

# 获取该目录下所有文件,存入列表中
fileList = os.listdir(path)

n = 0
for i in fileList:
    # 设置旧文件名(就是路径+文件名)
    oldname = path + os.sep + fileList[n]  # os.sep添加系统分隔符

    # 设置新文件名
    newname = path  + os.sep + 'ZhaoLiying' + str(n + 1) + '.JPG'

    os.rename(oldname, newname)  # 用os模块中的rename方法对文件改名
    print(oldname, '======>', newname)

    n += 1

爬虫:

import urllib.request as ur
import os
import string
import threading
import re
import requests
import sys


def get_image(keyworld, pn, rn, type, i):
    try:
        url = ur.quote(
            'https://image.baidu.com/search/acjson?tn=resultjson_com&ipn=rj&ct=201326592&is=&fp=result'
            '&queryWord=' + keyworld + '&cl=2&lm=-1&ie=utf-8&oe=utf-8&adpicid=&st=-1&z=&ic=0&word=' + keyworld +
            '&s=&se=&tab=&width=&height=&face=0&istype=2&qc=&nc=1&fr=&pn=' + str(pn) + '&rn=' + str(
                rn) + '&gsm=1e&1529504588260=',
            safe=string.printable)
        req = ur.Request(url)
        req.add_header("User-Agent", "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:47.0) Gecko/20100101 Firefox/47.0")
        html1 = ur.urlopen(url, timeout=600).read()
        html1 = str(html1)

        pat1 = '"thumbURL":".+?",'
        pat2 = 'https:.+?.jpg'
        thumbURLs = re.compile(pat1).findall(html1)
        imageURLs = re.compile(pat2).findall(str(thumbURLs))

        save_dir = type + '/' + type + i + '/'
        if os.path.exists(save_dir) is False:
            os.makedirs(save_dir)
        num = 1
        for index, imageurl in enumerate(imageURLs):
            try:
                data = ur.urlopen(imageurl, timeout=20).read()
                fd = open(save_dir + type + '_' + str(pn) + '_' + str(index) + '.jpg', "wb")
                fd.write(data)
                fd.close()
                sys.stdout.write('下载成功%s\r' % num)
                sys.stdout.flush()
                num = num + 1
            except Exception as e:
                print('保存图片异常:' + e)
    except Exception as e:
        print('获取图片url异常:' + e)


if __name__ == '__main__':
    ai = input("Input key: ")
    bi = input("Input num: ")
    for i in range(int(bi)):
        get_image(ai, i * 50, 50, ai, str(i))
    # tA = ThreadA()
    # tA.start()


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值