python - 圖片爬蟲時(shí)候遇到問題 urllib.request.urlretrieve 下載到指定文件夾不成功?
問題描述
如果下載到D盤也是沒有問題的,下載到我建立的目錄下就有問題(主要是我想在D盤建立以URL這個(gè)問號前面的數(shù)字為名字的目錄如(http://v.yupoo.com/photos/196...’)中的46975340就是不行,因?yàn)橛泻芏噫溄樱總€(gè)鏈接的這個(gè)數(shù)字不同,我想用這個(gè)數(shù)字作為文件夾的名字,存放這個(gè)鏈接下載下來的圖片)源碼如下: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.intensediesel.com/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í)行報(bào)錯(cuò):(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)
報(bào)錯(cuò)信息如下: (和上面一樣)
File 'C:Python36liburllibrequest.py', line 258, in urlretrieve
tfp = open(filename, ’wb’)
FileNotFoundError: [Errno 2] No such file or directory: ’d:469753400.jpg’
請教給位大大,這個(gè)路徑到底有什么問題沒有?應(yīng)該怎么寫。
問題解答
回答1:在保存之前,先檢查一下目錄是否存在,不存在則建立
if not os.path.exists(file_path): os.mkdir(file_path)
相關(guān)文章:
1. 數(shù)據(jù)庫 - MySQL 單表500W+數(shù)據(jù),查詢超時(shí),如何優(yōu)化呢?2. javascript - 百度echarts series數(shù)據(jù)更新問題3. 求大神幫我看看是哪里寫錯(cuò)了 感謝細(xì)心解答4. MySQL客戶端吃掉了SQL注解?5. mac 安裝 python_MySQLdb6. javascript - 圖片能在網(wǎng)站顯示,但控制臺仍舊報(bào)錯(cuò)403 (Forbidden)7. php自學(xué)從哪里開始?8. mysql - AttributeError: ’module’ object has no attribute ’MatchType’9. python小白的基礎(chǔ)問題 關(guān)于while循環(huán)的嵌套10. phpstady在win10上運(yùn)行
