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='http://www.lshqa.cn/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 - node.js promise沒用2. golang - 用IDE看docker源碼時的小問題3. yii2中restful配置好后在nginx下報404錯誤4. 算法 - python 給定一個正整數a和一個包含任意個正整數的 列表 b,求所有<=a 的加法組合5. android 如何實現如圖中的鍵盤上的公式及edittext的內容展示呢6. java - 我在用Struts2上傳文件時,報以下錯誤怎么回事?7. c++ - 如何正確的使用QWebEngineView?8. PHP注冊功能9. php - TP5的登錄驗證問題10. php - 注冊驗證郵箱失效后操作問題
