【问题标题】:Download multiple xls files using Python使用 Python 下载多个 xls 文件
【发布时间】:2015-02-12 23:17:49
【问题描述】:

我想知道这里是否有人可以帮助我创建脚本?我以前从来没有做过这样的事情,所以我不知道我在做什么。但是我已经读了几天了,但我仍然不理解它,所以我很感激我能得到的所有帮助。我什至愿意为你的服务付费!

这是我的问题的一个例子。目前,我在我的 Windows 桌面上保存了一个名为“Stars”的 CSV 文件,其中包含大约 50.000 个不同的链接,当按下这些链接时,它们会直接开始下载 xls 文件。每行都包含这些链接之一。我希望在您的帮助下为此创建某种脚本,该脚本将通过每一行进行某种循环并访问这些不同的链接,以便它可以下载这 50.000 个不同的文件。

感谢大家花时间阅读本文

/莎拉

【问题讨论】:

  • 那么如果你想在python做这个,你为什么要标记这个问题php
  • 哦,我现在就修复它,如果可以用 php 也可以,不需要在 python 中使用它
  • @SarahPolley 也删除标签bash。你能提供一个行结构吗?混淆链接
  • 已删除!一行看起来像 nasa.com/vps/Stars/excel/… 所有链接都包含此文本,只有数字发生变化
  • 我不知道你说的是不是这个?我的英语不是最好的

标签: python csv windows-7


【解决方案1】:

假设您的 CSV 文件如下所示:

http://www.ietf.org/rfc/rfc959.txt
http://www.ietf.org/rfc/rfc1579.txt
http://www.ietf.org/rfc/rfc2577.txt

替换python代码中csvfiletargetdir的路径:

import os
import urllib2

csvfile = '/tmp/links.csv'
targetdir = '/tmp/so'

with open(csvfile) as links:
    for link in links:
        filename = link.split('/')[-1].strip()
        filepath = os.path.join(targetdir, filename)
        print 'Downloading %s \n\t .. to %s' % (link.strip(), filepath)
        with open(filepath, 'w') as data:
            xlsfile = urllib2.urlopen(link)
            data.writelines(xlsfile)

使用示例:

$ python download_all.py
Downloading http://www.ietf.org/rfc/rfc959.txt
     .. to /tmp/so/rfc959.txt
Downloading http://www.ietf.org/rfc/rfc1579.txt
     .. to /tmp/so/rfc1579.txt
Downloading http://www.ietf.org/rfc/rfc2577.txt
     .. to /tmp/so/rfc2577.txt

$ dir -1 /tmp/so
rfc1579.txt
rfc2577.txt
rfc959.txt

祝你好运。

【讨论】:

  • @SarahPolley 可能你在 python3 中使用。你能发布一个完整的错误吗?尝试删除 print 语句和 windows 的转义路径,即双反斜杠:C:\\tmp\\whatever
  • 现在,当我尝试在 Python IDLE 中运行脚本时,我收到无效的语法错误,并且 this -> ' code import os import urllib2 csvfile = 'C:\Program Files\Python 3.5\input.csv' targetdir = 'C:\Users\Desktop\output' 以 open(csvfile) 作为链接:对于链接中的链接:filename = link.split('/')[-1].strip() 文件路径= os.path.join(targetdir, filename) print 'Downloading %s \n\t .. to %s -> ' code
【解决方案2】:

另一种解决方案:

如果没有更多信息,我可以在这个问题上给你的最佳答案是使用 Selenium 下载文件并使用 csv 模块来解析带有链接的 csv。

例子:

import csv
from selenium import webdriver

profile = webdriver.FirefoxProfile()
profile.set_preference('browser.download.folderList', 2)
profile.set_preference('browser.download.manager.showWhenStarting', False)
profile.set_preference('browser.download.dir', 'PATH\TO\DOWNLOAD\DIRECTORY')
profile.set_preference('browser.helperApps.neverAsk.saveToDisk', "application/csv")
driver = webdriver.Firefox(firefox_profile=profile)

input_csv_location = "PATH\TO\CSV.csv"

with open(csv_location, 'r') as input_csv:
    reader = csv.reader(input_csv)
    for line in reader:
        driver.get(line[0])

这假设 csv 上没有标题,并且 url 位于 Spot numero uno 中。

【讨论】:

    猜你喜欢
    • 2019-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-12
    相关资源
    最近更新 更多