2016-06-27 5 views
0

웹 사이트에서 여러 단어 문서를 반복 할 수있는 폴더에 다운로드하려고합니다. 그들은 셰어 포인트 목록에 호스팅되어 있으며, 이미 HTML 코드를 파싱하여 이러한 단어 문서에 대한 모든 링크 목록을 컴파일 할 수있었습니다. 이 링크를 클릭하면 단어 문서를 열거 나 저장하라는 메시지가 나타납니다. 이 연결의 끝에서, doc라는 단어의 제목도 거기에 있습니다. URL 문자열을 분할하여 내 URL 목록과 일치하는 단어 문서의 이름 목록을 가져올 수있었습니다. 내 목표는 모든 URL을 통과하고 모든 단어 문서를 폴더로 다운로드하는 루프를 작성하는 것입니다. 편집 - 내 코드 - ... 고려 @DeepSpace 고려하고 @aneroid의 제안을 (그리고이를 구현하기 위해 최선을 다하고)URL에서 워드 문서를 파이썬의 지정된 디렉토리에있는 폴더로 다운로드하는 방법은 무엇입니까?

import requests 
from requests_ntlm import HttpNtlmAuth 
import shutil 

def download_word_docs(doc_url, doc_name): 
    r = requests.get(doc_url, auth=HttpNtlmAuth(domain\\user, pass), stream=True) 
    with open(doc_name, 'wb') as f:                                     
     shutil.copyfileobj(r.raw, f) #where's it copying the fileobj to? 

는 내 요청이 다운로드에 있기 때문에이 이미지와 다른 생각 링크가 아닌 물리적 인 jpeg 이미지 ... 나는 틀릴 수도 있지만 이것은 까다로운 상황입니다.

내 프로그램이 .docx를 지정된 경로 (설정할 수있는 폴더)에 다운로드 (또는 복사본 만들기)하려고하는 중입니다. 현재 그것은 admin 명령 프롬프트 (나는 Windows에있어)에서 오류없이 실행되지만 파일을 복사하는 위치를 알지 못합니다. 내 희망은 내가 하나를 얻을 수있는 경우 URL 목록에 반복하는 방법을 알아낼 수 있습니다. 지금까지 도움을 주신 분들 (@DeepSpace 및 @aneroid). 코드에서

+0

기본적으로 가능하면

  • 그렇지 않은 경우는, 파일 이름과 URL의 끝을 사용 파이썬은 작업 디렉토리와 같은 폴더를 프로그램에서 사용할 것이므로 파일을 넣을 것을 기대합니다. 그러나'download_word_docs'가 전혀 호출되지 않을 가능성이 있습니까? 'print ("download_word_docs는")'문을 추가하면 실제로 출력됩니까? –

  • 답변

    0

    , 당신은 "개방/새 파일을 작성을 방지하고 직접 다운로드 할 수있는 방법?"

    언급 한

    는 더 다운로드 직접 없습니다. 브라우저는 코드를 통해 작성하려는 것과 유사합니다. 그들은 서버 또는 URL에 의해 지정된 이름으로 "새 파일 만들기"입니다.

    나는 뭔가 다른 몇 일 전에 쓴, 그리고 유사한 answer linked by @DeepSpace :

    def save_link(book_link, book_name): 
        the_book = requests.get(book_link, stream=True) 
        with open(book_name, 'wb') as f: 
         for chunk in the_book.iter_content(1024 * 1024 * 2): # 2 MB chunks 
          f.write(chunk) 
    

    book_name 다른 함수에 book_link의 텍스트에서 검색되었지만 당신은 또한이 작업을 수행 할 수있는 작업 :

    1. 응답 헤더에 파일 이름이 포함되어 있는지 확인하십시오.

      >>> the_link = 'http://example.com/some_path/Special%20document.doc' 
      >>> filename = urllib.unquote_plus(the_link.split('/')[-1]) 
      >>> print filename 
      Special document.doc 
      >>> # then do 
      ... with open(filename, 'wb') as f: 
      .... # etc. 
      
    -1

    이 코드를 시도하고 볼 당신을 위해 작동하는 경우 :

    from urllib.request import Request, urlopen 
    
    def get_html(url, timeout = 15): 
        ''' function returns html of url 
        usually html = urlopen(url) is enough but sometimes it doesn't work 
        also instead urllib.request you can use any other method to get html 
        code of url like urllib or urllib2 (just search it online), but I 
        think urllib.request comes with python installation''' 
    
        html = '' 
        try: 
         html = urlopen(url, None, timeout) 
        except: 
         url = Request(url, headers={'User-Agent': 'Mozilla/5.0'}) 
         try: 
          html = urlopen(url, None, timeout) 
         except: 
          pass 
        return html 
    
    def get_current_path(): 
        ''' function returns path of folder in which python program is saved''' 
    
        try: 
         path = __file__ 
        except: 
         try: 
          import sys 
          path = sys.argv[0] 
         except: 
          path = '' 
        if path: 
         if '\\' in path: 
          path = path.replace('\\', '/') 
         end = len(path) - path[::-1].find('/') 
         path = path[:end] 
        return path 
    
    def check_if_name_already_exists(name, path, extension): 
        ''' function checks if there is already existing file 
        with same name in folder given by path.''' 
    
        try: 
         file = open(path + name + extension, 'r') 
         file.close() 
         return True 
        except: 
         return False 
    
    def get_new_name(old_name, path, extension): 
        ''' functions ask user to enter new name for file and returns inputted name.''' 
    
        print('File with name "{}" already exist.'.format(old_name)) 
        answer = input('Would you like to replace it (answer with "r")\nor create new one (answer with "n") ? ') 
        while answer not in 'rRnN': 
         print('Your answer is inconclusive') 
         print('Please answer again:') 
         print('if you would like to replece the existing file answer with "r"') 
         print('if you would like to create new one answer with "n"') 
         answer = input('Would you like to replace it (answer with "r")\n or create new one (answer with "n") ? ') 
        if answer in 'nN': 
         new_name = input('Enter new name for file: ') 
         if check_if_name_already_exists(new_name, path, extension): 
          return get_new_name(new_name, path) 
         else: 
          return new_name 
        if answer in 'rR': 
         return old_name 
    
    def get_url_extension(url): 
        if url[::-1].find('cod.') == 0: 
         return '.doc' 
        if url[::-1].find('xcod.') == 0: 
         return '.docx' 
    
    def download_word(url, name = 'document', path = None): 
        '''function downloads word file from its url 
        required argument is url of pdf file and 
        optional argument is name for saved pdf file and 
        optional argument path if you want to choose where is your file saved 
        variable path must look like: 
         'C:\\Users\\Computer name\\Desktop' or 
         'C:/Users/Computer name/Desktop' ''' 
        # and not like 
        # 'C:\Users\Computer name\Desktop' 
    
        word = get_html(url) 
        extension = get_url_extension(url) 
    
        name = name.replace(extension, '') 
        if path == None: 
         path = get_current_path() 
        if '\\' in path: 
         path = path.replace('\\', '/') 
        if path[-1] != '/': 
         path += '/' 
        if path: 
         check = check_if_name_already_exists(name, path, extension) 
         if check: 
          if name == 'document': 
           i = 1 
           name = 'document(' + str(i) + ')' 
           while check_if_name_already_exists(name, path, extension): 
            i += 1 
            name = 'document(' + str(i) + ')' 
          else: 
           name = get_new_name(name, path, extension) 
         file = open(path+name + extension, 'wb') 
        else: 
         file = open(name + extension, 'wb') 
    
        file.write(word.read()) 
        file.close() 
        if path: 
         print(name + extension + ' file downloaded in folder "{}".'.format(path)) 
        else: 
         print(name + extension + ' file downloaded.') 
        return 
    
    
    download_url = 'http://www.scripps.edu/library/open/instruction/googletips.doc' 
    download_url = 'http://regionblekinge.se/a/uploads/dokument/demo.docx' 
    download_word(download_url) 
    
    +0

    당신이 downvote 때 코멘트를 추가하십시오 – ands

    관련 문제