挂梯子后出现访问https报错信息报 hostname xxxx的错误,requests不到链接,解决方法
需求:读Excel中第一列作为文件夹名,第二列开始都是图片链接,图片链接可以有多条,每一行可以图片链接数不一,把每一行的图片下载到指定文件夹中。 test.xlsx例如:
import pandas as pd
import requests
import numpy as np
import re
import os
import time
data = pd.DataFrame(pd.read_excel('test.xlsx', 'Sheet1'))
print(data)
print(data.values[0:, 0])
i=0
row =0
for dir_name in data.values[0:,0]:
dir_name_real = re.sub(r'[/\:*"<>|?\n]*', '', str(dir_name))
os.mkdir(dir_name_real)
for column in range(1,data.shape[1]):
if pd.isna(data.iloc[row].iat[column])==False:
website =data.iloc[row].iat[column]
print(website)
print("*"*50)
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36'
}
try:
requests.packages.urllib3.disable_warnings()
response = requests.get(website, headers=headers,verify = False,timeout=10)
print(response.status_code)
if response.status_code == 200:
response.encoding = response.apparent_encoding
patten = "https://.*/(.+).jpg|https://.*/(.+).png"
if website[-3:] == 'jpg':
with open("./" + dir_name_real + "/" + str(re.search(patten, website).group(1)) + ".jpg", "wb") as f:
print("正在保存第 %d 个网站的图片" % (i + 1))
f.write(response.content)
print("已保存第 %d 个网站的图片" % (i + 1))
i += 1
else:
with open("./" + dir_name_real + "/" + str(re.search(patten, website).group(2)) + ".jpeg", "wb") as f:
print("正在保存第 %d 个网站的图片" % (i + 1))
f.write(response.content)
print("已保存第 %d 个网站的图片" % (i + 1))
i += 1
except:
website = ""
break;
else:
website = ""
break;
row+=1
|