python - 图片爬虫时候遇到问题 urllib.request.urlretrieve 下载到指定文件夹不成功?
问题描述
如果下载到D盘也是没有问题的,下载到我建立的目录下就有问题(主要是我想在D盘建立以URL这个问号前面的数字为名字的目录如(http://v.yupoo.com/photos/196...’)中的46975340就是不行,因为有很多链接,每个链接的这个数字不同,我想用这个数字作为文件夹的名字,存放这个链接下载下来的图片)源码如下:
import urllib.requestimport reimport os
url_all =[’http://v.yupoo.com/photos/196...’,’http://v.yupoo.com/photos/196...’,’http://v.yupoo.com/photos/196...’,’http://v.yupoo.com/photos/196...’,]
def getHtml(url):
html = urllib.request.urlopen(url).read()return html通过正则获取图片
def getImg(html):
reg = ’src='https://www.haobala.com/wenda/(.+?.jpg)'’imgre = re.compile(reg)imglist = re.findall(imgre,html)
# print(imglist)
return imglist
for i in range(len(url_all)):
循环把图片存到本地html = getHtml(url_all[i])list=getImg(html.decode())print (url_all[1])
x = 0for imgurl in list: print(x) filename = os.path.dirname(url_all[i])filename2 = os.path.basename(filename)os.mkdir(’d:%s’% filename2)
local=’D:%s%s.jpg’ %(filename2,x) print (local) urllib.request.urlretrieve(imgurl,local) x+=1print('done')
执行报错:(win10的64位系统,python3.6)
File 'C:Python36liburllibrequest.py', line 258, in urlretrieve
tfp = open(filename, ’wb’)
FileNotFoundError: [Errno 2] No such file or directory: ’d:469753400.jpg’经测试最后一句这么写是可以输出的: urllib.request.urlretrieve(imgurl,’d:%s.jpg’% str(i*10+x))
经测试 前面两句都没有问题,加第三句: local=’d:%s%s.jpg’ %(filename2,x)
print (local)
urllib.request.urlretrieve(imgurl,local)
报错信息如下: (和上面一样)
File 'C:Python36liburllibrequest.py', line 258, in urlretrieve
tfp = open(filename, ’wb’)
FileNotFoundError: [Errno 2] No such file or directory: ’d:469753400.jpg’
请教给位大大,这个路径到底有什么问题没有?应该怎么写。
问题解答
回答1:在保存之前,先检查一下目录是否存在,不存在则建立
if not os.path.exists(file_path): os.mkdir(file_path)
相关文章:
1. javascript - 像这种内联Js绑定方式,如何定位到js代码?2. python - 一个程序中的切片问题3. module - python模块from import语句相对导入,加不加点号有什么区别?4. [python2]local variable referenced before assignment问题5. java - 微信小程序中 无缘无故的提示(图片的加载失败)6. python - TypeError: tryMsgcode() takes exactly 2 arguments (0 given)7. python - 为什么用time.strftime格式化会用默认值?8. javascript - .vue页面跳转问题9. javascript - 求一款靠谱点的移动端图片查看器插件,老司机速进!10. javascript - vue-cli中 用proxyTable实现了跨域,用get访问没有问题,但通过 post传数据就出现了问题

网公网安备