2012-04-25 3 views
0

이 스크립트가 링크 이름에서 "nmv-fas"를 가져 와서 해당 이름의 디렉토리를 만든 다음 해당 디렉토리에 다운로드 한 모든 파일을 배치하려면 어떻게해야합니까?파이썬에서 폴더 생성

all.html : 폴더에 저장

<a href="http://www.youversion.com/bible/gen.45.nmv-fas">http://www.youversion.com/bible/gen.45.nmv-fas</a> 
<a href="http://www.youversion.com/bible/gen.46.nmv-fas">http://www.youversion.com/bible/gen.46.nmv-fas</a> 
<a href="http://www.youversion.com/bible/gen.47.nmv-fas">http://www.youversion.com/bible/gen.47.nmv-fas</a> 
<a href="http://www.youversion.com/bible/gen.48.nmv-fas">http://www.youversion.com/bible/gen.48.nmv-fas</a> 
<a href="http://www.youversion.com/bible/gen.49.nmv-fas">http://www.youversion.com/bible/gen.49.nmv-fas</a> 
<a href="http://www.youversion.com/bible/gen.50.nmv-fas">http://www.youversion.com/bible/gen.50.nmv-fas</a> 
<a href="http://www.youversion.com/bible/exod.1.nmv-fas">http://www.youversion.com/bible/exod.1.nmv-fas</a> 
<a href="http://www.youversion.com/bible/exod.2.nmv-fas">http://www.youversion.com/bible/exod.2.nmv-fas</a> 
<a href="http://www.youversion.com/bible/exod.3.nmv-fas">http://www.youversion.com/bible/exod.3.nmv-fas</a>  

파일 이름 :

nmv-fas 

파이썬 :

import lxml.html as html 
import urllib 
import urlparse 
from BeautifulSoup import BeautifulSoup 
import re 

root = html.parse(open('all.html')) 
for link in root.findall('//a'): 
    url = link.get('href') 
    name = urlparse.urlparse(url).path.split('/')[-1] 
    f = urllib.urlopen(url) 
    s = f.read() 
    f.close() 
    soup = BeautifulSoup(s) 
    articleTag = soup.html.body.article 
    converted = str(articleTag) 
    open(name, 'w').write(converted) 

답변

1

당신은 파일의 아웃 링크를 구문 분석 lxml 모듈을 사용할 수 있습니다 그런 다음 urllib을 사용하여 각 링크를 다운로드하십시오. 링크를 읽는 것은 다음과 같습니다

import lxml.html as html 

root = html.parse(open('links.html')) 
for link in root.findall('//a'): 
    url = link.get('href') 

당신은 urllib.urlopen를 사용하여 파일에 대한 링크를 다운로드 할 수 있습니다

import urllib 
import urlparse 

# extract the final path component and use it as 
# the local filename. 
name = urlparse.urlparse(url).path.split('/')[-1] 

fd = urllib.urlopen(url) 
open(name, 'w').write(fd.read()) 

함께이 넣고 당신은 당신이 원하는 것과 유사한 무언가를해야한다.

+0

마지막 링크 만 다운로드하는 것 외에는 매우 잘 작동합니다. 모두 – Blainer

+1

오, 안됩니다. 함께 넣어 주면 올바르게 작동합니다. 당신은 단지 생각없이 복사하고 붙여 넣는 것입니다. 어쩌면 루프에 * 넣을 필요가 있습니다. – larsks

+0

그래, 내가 무슨 일을하는지 모르겠다. – Blainer