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://m.4tl426be.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. python - 數據與循環次數對應不上2. mysql - 把一個表中的數據count更新到另一個表里?3. 請教使用PDO連接MSSQL數據庫插入是亂碼問題?4. mysql - 分庫分表、分區、讀寫分離 這些都是用在什么場景下 ,會帶來哪些效率或者其他方面的好處5. Python爬蟲如何爬取span和span中間的內容并分別存入字典里?6. 視頻文件不能播放,怎么辦?7. mysql 查詢身份證號字段值有效的數據8. python - 爬蟲模擬登錄后,爬取csdn后臺文章列表遇到的問題9. node.js - nodejs開發中常用的連接mysql的庫10. 黑客 - Python模塊安全權限
