帮小弟我看下小弟我这个脚本为什么不能创建文件
大虾帮我看下我这个脚本为什么不能创建文件?
注释掉PRINT可以正常输出文件名,但是创建文件的时候,报错:" ioerror:[error 2] no such file or directory '' "
------解决方案--------------------
试了一下,循环中的第一次fname输出来的是空字符'',以后能正常输出,改了一句代码你试试看?
import urllib.request
import re,os
a = urllib.request.urlopen('http://www.daomubiji.com').read().decode('utf-8')
urls=re.findall('<a.*?href=(.*?\.html.*?)<\/a>',a,re.I)
for i in urls:
url = i.split('"')[1]
fname = url.split('/')[3]
#print(str(fname))
b = urllib.request.urlopen(url).read()
f = open(str(fname), 'w')
f.write(str(b))
f.close()
注释掉PRINT可以正常输出文件名,但是创建文件的时候,报错:" ioerror:[error 2] no such file or directory '' "
------解决方案--------------------
试了一下,循环中的第一次fname输出来的是空字符'',以后能正常输出,改了一句代码你试试看?
import urllib.request
import re,os
a = urllib.request.urlopen('http://www.daomubiji.com').read().decode('utf-8')
urls=re.findall('<a.*?href=(.*?\.html.*?)<\/a>',a,re.I)
for i in urls:
url = i.split('"')[1]
if url.split('/')[3]=='':
fname = url.split('/')[2]
else:
fname = url.split('/')[3]
#fname = url.split('/')[3]
#print(str(fname))
b = urllib.request.urlopen(url).read()
f = open(str(fname), 'w')
f.write(str(b))
f.close()