【问题标题】:can python be useful to open multiple tabs in a browser in one shot?python可以一次在浏览器中打开多个选项卡吗?
【发布时间】:2012-12-22 17:41:27
【问题描述】:

我正在寻找一种更快的方式来完成我的任务。我有 40000 个文件可下载的 url。我想在本地桌面上下载它们。现在我的想法是目前我正在做的是将链接放在浏览器上,然后通过脚本下载它们。现在我正在寻找的是在一个块中放置 10 个 url地址栏,同时获取要下载的10个文件。如果可能的话,希望整体时间会减少。

对不起,我迟到了,这里是:

def _download_file(url, filename):
    """
    Given a URL and a filename, this method will save a file locally to the»
    destination_directory path.
    """
    if not os.path.exists(destination_directory):
        print 'Directory [%s] does not exist, Creating directory...' % destination_directory
        os.makedirs(destination_directory)
    try:
        urllib.urlretrieve(url, os.path.join(destination_directory, filename))
        print 'Downloading File [%s]' % (filename)
    except:
        print 'Error Downloading File [%s]' % (filename)


def _download_all(main_url):
    """
    Given a URL list, this method will download each file in the destination
    directory.
    """

    url_list = _create_url_list(main_url)
    for url in url_list:
        _download_file(url, _get_file_name(url))

谢谢,

【问题讨论】:

  • 我已经给出了代码,希望它能让你清楚地了解我拥有什么以及我在寻找什么!
  • 请重新打开这个问题,这是一个有效的问题!
  • 为什么要使用浏览器?这似乎是一个XY problem。要下载文件,我会使用 requests 之类的库(或对 wget 进行系统调用);例如,通过import requests 下载文件; r = requests.get('http://imgs.xkcd.com/comics/tech_support_cheat_sheet.png') ; with file('new_image.png', 'w') as f: f.write(r.content) ;其中每个分号应该是一个换行符(尽管在 cmets 中不能写入),它会下载图像并将其写入文件 new_image.png
  • @VBSlover 尝试让您的问题更易于阅读,然后重新命名以重新打开。

标签: python selenium python-2.7


【解决方案1】:

为什么要使用浏览器?这似乎是一个XY problem

要下载文件,我会使用requests 之类的库(或对wget 进行系统调用)。

类似这样的:

import requests

def download_file_from_url(url, file_save_path):
    r = requests.get(url)
    if r.ok: # checks if the download succeeded
        with file(file_save_path, 'w') as f: 
           f.write(r.content)
        return True
    else:
        return r.status_code

download_file_from_url('http://imgs.xkcd.com/comics/tech_support_cheat_sheet.png', 'new_image.png')
# will download image and save to current directory as 'new_image.png'

您首先必须使用您喜欢的任何 python 包管理器安装请求,例如pip install requests。你也可以变得更漂亮;例如,

【讨论】:

    最近更新 更多