2017-02-15 106 views
0

我一直在努力刮板从网站上获取大量的HTML和图像。我有刮板工作,但目录大量填充,导致很难导航。我会如何将它保存到一个子目录? ,节省了HTML的一部分:保存文件到一个子目录

t = open(str(current)+".html", 'w+') 
t.write(b) 
t.close() 

而且一部分保存图像:

​​
+0

您可能想向我们展示您到目前为止的内容? – davidejones

+0

这不像改变你保存的路径那么简单吗?我们在这里错过了什么? – WillardSolutions

+0

我有相当多的代码,你需要看哪个特定的部分? –

回答

2

你只是向我们展示你的代码的一部分,这是无益的,与说写一个子目录很简单,但首先需要创建一个。现在,我只能给你几个基本的例子,因为我不知道你的代码的其他部分是什么样的,希望这里有所帮助!

def create_folder(self, path): 
     try: 
      if os.path.isdir(path): 
       print("Error: The directory you're attempting to create already exists") # or just pass 
      else: 
       os.makedirs(path) 
     except IOError as exception: 
      raise IOError('%s: %s' % (path, exception.strerror)) 
     return None 

或更容易

os.makedirs("C:\\Example Folder\\") 

或Linux的

os.makedirs('/home/' + os.getlogin() + '/Example Folder/') 

的情况下,然后就写它像往常一样,在刚刚提供的路径子目录。

def write(self, path, text): 
     try: 
      if os.path.isfile(path): 
       return None # or print and error, or pass etc... 
      else: 
       with open(path, 'w') as outFile: 
        outFile.write(text) 
     except IOError as exception: 
      raise IOError("%s: %s" % (path, exception.strerror)) 

     return None 
在这种情况下

,你就会把路径到您的子目录中的“路径”参数,并包含“文本”参数中的文本变量。您可以修改此功能追加,写字节等。

更新信息解决您的意见

一个非常简单的方法,使小规模的Python程序“更多”跨平台的,只是像做

if sys.platform == 'win32': 
    print('This is windows') 
elif sys.platform == 'linux2': 
    print('This is some form of linux') 

可以添加,检查操作系统,然后根据操作系统:)

是的,你是正确的,上面写功能也覆盖这些文件,你可以在文件中附加运行块(添加新没有overwriti的文字通过改变“W”标志“A”,像这样

def append(self, path, text): 
     try: 
      if os.path.isfile(path): 
       with open(path, 'a') as outFile: 
        outFile.write(text) 
     except IOError as exception: 
      raise IOError('%s: %s' % (path, exception.strerror)) 
     return None  

进一步更新纳克现有文本):

如果你不使用类你可以删除的“自我”。

根据你最近的评论是“我自己放什么”,我真的强烈建议你暂时放弃你的项目,并首先学习python的基础知识......你可以在以下地方找到教程。

https://www.tutorialspoint.com/python/

https://docs.python.org/3/tutorial/

如果您使用的是较旧的版本,你可以简单地切换到您所使用的官方网站哪一个,祝你好运,但不幸的是,我可以”在没有首先知道至少基本知识的情况下,你可以进一步帮助你,对不起!

+0

啊,那看起来不错。我可以使用try/except并将两种方法用于跨平台兼容性吗? –

+0

是的,你也可以通过简单的方式找出你正在使用的操作系统,使其更好。 – Afflicted

+0

你的代码写入文件似乎重写't.write()'会做什么。那是对的吗?如果是这样,我将如何使用此方法来保存图像? –