在python中创建文件夹
问题描述:
如何让此脚本从链接名称中获取“nmv-fas”并创建一个具有该名称的目录,然后放置所有下载到该目录中的文件。在python中创建文件夹
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)
答
您可以使用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())
一起把这些,你应该有类似你想要的东西。
它工作得很好,除了它只下载最后一个链接,不是所有的链接 – Blainer 2012-04-25 16:37:11
哦,不,如果你把它们正确地放在一起,它就可以正常工作。你只是在没有想到的情况下复制和粘贴。也许你需要把东西*放在循环中*。 – larsks 2012-04-25 16:37:58
是的男人我不知道我在做什么 – Blainer 2012-04-25 17:00:15