Python获取Excel中超链接并下载至本地

在这一任务的处理中,我是用的是 xlrd模块,它是用来读取Excel表格数据的模块。

  • 特别注意:高版本的xlrd目前去除了对xlsx格式的支持,仅支持 xls格式
xlrd.biffh.XLRDError: Excel xlsx file; not supported

针对以上问题,可以有两种选择:

  1. 选择重新安装低版本的:pip install xlrd==1.2.0
  2. 如果不想重新安装,可以打开xlsx文件将文件以xls格式另存储一份

所需要处理的文件情况如下所示:

import os
import xlrd
import requests
import time

from requests.packages.urllib3.exceptions import InsecureRequestWarning
# 禁用安全请求警告
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
base_path = "stuinfo/"
xlsx_filename = "rjtxjg.xls"

#读取excel文件
bk = xlrd.open_workbook(xlsx_filename)

#获取第一个sheet
sh1 = bk.sheets()[0]
print(sh1.nrows, sh1.ncols)

for r_index in range(40, sh1.nrows):
    print(sh1.cell_value(r_index, 2))
    os.mkdir(base_path + sh1.cell_value(r_index, 2))
    for c_index in range(3, sh1.ncols):
        if len(sh1.cell_value(r_index, c_index)) != 0:
            #获取超链接url
            link = sh1.hyperlink_map.get((r_index, c_index))
            print(link.url_or_path)

            #根据url下载到本地,这里需要注意https链接的话需要关闭认证
            filename = requests.get(link.url_or_path, verify=False)
            pic_name = base_path + sh1.cell_value(r_index, 2) + "/" + str(c_index) + ".jpg"
            print(pic_name)
            with open(pic_name, "wb") as code:
                code.write(filename.content)
        time.sleep(0.5)

 执行情况:

猜你喜欢

转载自blog.csdn.net/weixin_42067873/article/details/125597659
今日推荐