python - 圖片爬蟲時候遇到問題 urllib.request.urlretrieve 下載到指定文件夾不成功?
問題描述
如果下載到D盤也是沒有問題的,下載到我建立的目錄下就有問題(主要是我想在D盤建立以URL這個問號前面的數(shù)字為名字的目錄如(http://v.yupoo.com/photos/196...’)中的46975340就是不行,因為有很多鏈接,每個鏈接的這個數(shù)字不同,我想用這個數(shù)字作為文件夾的名字,存放這個鏈接下載下來的圖片)源碼如下:
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='http://www.leifengta.com.cn/wenda/(.+?.jpg)'’imgre = re.compile(reg)imglist = re.findall(imgre,html)
# print(imglist)
return imglist
for i in range(len(url_all)):
循環(huán)把圖片存到本地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')
執(zhí)行報錯:(win10的64位系統(tǒng),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’經(jīng)測試最后一句這么寫是可以輸出的: urllib.request.urlretrieve(imgurl,’d:%s.jpg’% str(i*10+x))
經(jīng)測試 前面兩句都沒有問題,加第三句: 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’
請教給位大大,這個路徑到底有什么問題沒有?應(yīng)該怎么寫。
問題解答
回答1:在保存之前,先檢查一下目錄是否存在,不存在則建立
if not os.path.exists(file_path): os.mkdir(file_path)
相關(guān)文章:
1. golang - 用IDE看docker源碼時的小問題2. docker images顯示的鏡像過多,狗眼被亮瞎了,怎么辦?3. 前端 - @media query 使用出現(xiàn)的問題?4. docker - 如何修改運行中容器的配置5. 運行python程序時出現(xiàn)“應(yīng)用程序發(fā)生異常”的內(nèi)存錯誤?6. 我何時應(yīng)該在Java中使用JFrame.add(component)和JFrame.getContentPane()。add(component)7. phpstudy8.1沒集成mysql-front8. 利用IPMI遠程安裝centos報錯!9. html5和Flash對抗是什么情況?10. docker-machine添加一個已有的docker主機問題

網(wǎng)公網(wǎng)安備