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)
4

1 に答える 1

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())

これらを組み合わせると、あなたが望むものに似たものが得られるはずです.

于 2012-04-25T16:26:19.783 に答える