您的位置:首頁技術文章
文章詳情頁

python - 圖片爬蟲時候遇到問題 urllib.request.urlretrieve 下載到指定文件夾不成功?

瀏覽:124日期:2022-07-12 15:08:10

問題描述

如果下載到D盤也是沒有問題的,下載到我建立的目錄下就有問題(主要是我想在D盤建立以URL這個問號前面的數字為名字的目錄如(http://v.yupoo.com/photos/196...’)中的46975340就是不行,因為有很多鏈接,每個鏈接的這個數字不同,我想用這個數字作為文件夾的名字,存放這個鏈接下載下來的圖片)源碼如下:python - 圖片爬蟲時候遇到問題 urllib.request.urlretrieve 下載到指定文件夾不成功?import urllib.requestimport reimport os

py抓取頁面圖片并保存到本地獲取頁面信息

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.wxshucaidpc.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)

標簽: Python 編程
相關文章:
国产综合久久一区二区三区