最短脚本下载文件

今天遇到一个题,给定一个文本文件,每一行一个 url,用脚本把他们下载回来,语言不限,越短越好

简短这种事情首先想起 python

import urllib

f = open("url.txt", "r")
for line in f:
    urllib.urlretrieve(line, line[line.rfind("/") + 1:-1])
f.close()

准备的 url.txt,需要注意最后有一个空行

https://www.google.com/images/…
http://www.baidu.com/img/baidu…

运行结果

下面试试 php 的,注意小心处理行尾的换行符 rn

<?php
$f = fopen("url.txt","r");
while (!feof($f)) {
  $line = fgets($f);
  if ( ! empty($line)) {
    file_put_contents(substr($line, strrpos($line, "/")+1, strlen($line)-strrpos($line, "/")-3), file_get_contents(substr($line, 0, strlen($line)-2)));
  }
}
fclose($f);

测试数据,同上,需要一个空行,另外,php 默认无法访问 https,所以改了 google 那行

http://www.baidu.com/img/baidu…
http://p1.qhimg.com/d/_hao360/…

效果

Leave a Reply

Your email address will not be published. Required fields are marked *