【问题标题】:create folder in python在python中创建文件夹
【发布时间】:2012-04-25 16:13:47
【问题描述】:

如何让这个脚本从链接名称中获取“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)

【问题讨论】:

    标签: python html mechanize lxml


    【解决方案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())
    

    把这些放在一起,你应该会得到与你想要的相似的东西。

    【讨论】:

    • 效果很好,只是它只下载最后一个链接,而不是全部
    • 哦,不,如果你把它们正确地放在一起,它就可以了。你只是不假思索地复制和粘贴。也许您需要在 循环内放一些东西
    • 没关系,我想通了。我没有意识到 python 在格式和语法方面有多严格。
    • 太棒了。如果此答案对您有所帮助,请考虑通过检查问题左侧的复选标记将其标记为“已接受”。干杯!
    猜你喜欢
    • 2014-04-09
    • 1970-01-01
    • 2018-12-10
    • 2021-07-02
    • 2010-12-07
    • 2018-10-01
    • 1970-01-01
    • 2018-12-02
    • 2019-05-17
    相关资源
    最近更新 更多