2017-10-03 11 views
1

URL에서 일부 파일을 다운로드하고 있습니다.URL에서 파일을 다운로드 할 때 경로를 지정하십시오.

내가 이렇게 내 파일을 현재에 액세스 할 수 있습니다

import requests 
from bs4 import BeautifulSoup 
import os 

prefix = 'https://n5eil01u.ecs.nsidc.org/MOST/MOD10A1.006/' 
download_url = "https:/path_to_website" 

s = requests.session()               
soup = BeautifulSoup(s.get(download_url).text, "lxml") 

for a in soup.find_all('a', href=True): 

    final_link = os.path.join(prefix, a['href']) 
    result = s.get(final_link, stream = True) 
    with open(a['href'], 'wb') as out_file: 
      shutil.copyfileobj(result.raw, out_file) 

이 잘 파일을 다운로드하여 C의 기본 디렉토리에 넣는다합니다 :/사용자.

내 파일을 어디에서 다운로드 할 것인지 선택하고 싶습니다. 당신은 outpath가 wget와 함께있는 곳을 선택할 수 있습니다.

는이 같은 wget와 함께이 시도 :

out_path = "C:/my_path" 
prefix = 'https://n5eil01u.ecs.nsidc.org/MOST/MOD10A1.006/' 

s = requests.session()               
soup = BeautifulSoup(s.get(download_url).text, "lxml") 

for a in page.find_all('a', href=True): 

    final_link = os.path.join(prefix, a['href']) 
    download = wget.download(final_link, out = out_path) 

내가 인증 (도시하지 않음)와 웹 사이트에 접속하고 있기 때문에 wget을 작동하지 않는 생각하지, 내가 마지막 링크에 가입 할 때 나는 더 이상이다 인증을 통해 액세스하십시오. shutil로 outpath를 지정하는 방법이 있습니까?

답변

1

os.path.join(out_path, a['href'])으로 열린 파일의 경로를 바꿔 첫 번째 방법을 사용하면 어떨까요? 당신은 다음과 같은 대상 경로를 만들 수 있습니다

import requests 
from bs4 import BeautifulSoup 
import os 

out_path = "C:\\my_path"  
prefix = 'https://n5eil01u.ecs.nsidc.org/MOST/MOD10A1.006/' 
download_url = "https:/path_to_website" 

s = requests.session()               
soup = BeautifulSoup(s.get(download_url).text, "lxml") 

for a in soup.find_all('a', href=True): 
    final_link = os.path.join(prefix, a['href']) 
    result = s.get(final_link, stream = True) 
    new_file_path = os.path.join(out_path, a['href']) 
    with open(new_file_path, 'wb') as out_file: # this will create the new file at new_file_path 
      shutil.copyfileobj(result.raw, out_file) 
+0

아, 그렇군요. 고맙습니다. –

0

,

target_path = r'c:\windows\temp' 
with open(os.path.join(target_path, a['href']), 'wb') as out_file: 
    shutil.copyfileobj(result.raw, out_file)