如何获取wget下载的文件的文件名
How to get filename of the file downloaded by wget
我正在使用 os.system('wget '+ link)
从网站检索文件。下载后,我想根据源links.
进一步处理这些文件
大多数link都是这种形式
htttp://example.com/.../filename.zip
.
在这种情况下,文件会简单地下载为 filename.zip
。我可以使用 basename
和 RegExp [^/]+$
从 link 中提取。
但问题是 links 的形式
http://http://www.ez-robot.com
http://www.worldscientific.com/
http://www.fairweld.com
这些 link 被下载为 index.html
、index.html.1
、index.html.2
等。
在这里,我无法区分哪个 index
文件属于哪个网站。我可以做到这一点的一种方法是查看 link 传递给 wget
的顺序。
我想要一些通用的方法来获取 'real' 文件名,文件通过该文件下载到计算机中。当 wget
完成执行时,它会在终端上显示一个 Saving to:
标签,后跟 'real' 文件名。我想将该文件名存储在一个字符串中。
是否存在任何direct/easier方法来获取文件名?我正在使用 Python.
$ wget http://www.fairweld.com
--2015-04-11 18:51:48-- http://www.fairweld.com/
Connecting to 202.142.81.24:3124... connected.
Proxy request sent, awaiting response... 200 OK
Length: 39979 (39K) [text/html]
Saving to: ‘index.html.4
您遇到的问题是因为文件名已经存在。我建议将每个 'file' 下载到一个新文件夹(即域名)以防止重复。
$ wget --directory-prefix=$DOMAIN $URL
这将保留原始文件名,如数据 headers 中指定的那样。
还有一个提示,您正在使用 os.system('wget '+ link)
这可能非常不安全,因为您没有在此处清理您的输入。输入可能会受到注入,这会使您的系统 运行 不需要的命令。在 Bobby Tables.
上阅读更多内容
使用os.path.basename根据url结尾获取名字,也可以使用requests下载html:
links = ["http://www.ez-robot.com",
"http://www.worldscientific.com/",
"http://www.fairweld.com"]
import urlparse
import requests
import os
for link in links:
r = requests.get(link)
if link.rsrip("/").endswith(".com"):
name = os.path.basename(link)
else:
name = urlparse.urlsplit(link.path.split("/")[-1])
with open("{}.html".format(name),"w") as f:
f.write(r.content)
我正在使用 os.system('wget '+ link)
从网站检索文件。下载后,我想根据源links.
大多数link都是这种形式
htttp://example.com/.../filename.zip
.
在这种情况下,文件会简单地下载为 filename.zip
。我可以使用 basename
和 RegExp [^/]+$
从 link 中提取。
但问题是 links 的形式
http://http://www.ez-robot.com
http://www.worldscientific.com/
http://www.fairweld.com
这些 link 被下载为 index.html
、index.html.1
、index.html.2
等。
在这里,我无法区分哪个 index
文件属于哪个网站。我可以做到这一点的一种方法是查看 link 传递给 wget
的顺序。
我想要一些通用的方法来获取 'real' 文件名,文件通过该文件下载到计算机中。当 wget
完成执行时,它会在终端上显示一个 Saving to:
标签,后跟 'real' 文件名。我想将该文件名存储在一个字符串中。
是否存在任何direct/easier方法来获取文件名?我正在使用 Python.
$ wget http://www.fairweld.com
--2015-04-11 18:51:48-- http://www.fairweld.com/
Connecting to 202.142.81.24:3124... connected.
Proxy request sent, awaiting response... 200 OK
Length: 39979 (39K) [text/html]
Saving to: ‘index.html.4
您遇到的问题是因为文件名已经存在。我建议将每个 'file' 下载到一个新文件夹(即域名)以防止重复。
$ wget --directory-prefix=$DOMAIN $URL
这将保留原始文件名,如数据 headers 中指定的那样。
还有一个提示,您正在使用 os.system('wget '+ link)
这可能非常不安全,因为您没有在此处清理您的输入。输入可能会受到注入,这会使您的系统 运行 不需要的命令。在 Bobby Tables.
使用os.path.basename根据url结尾获取名字,也可以使用requests下载html:
links = ["http://www.ez-robot.com",
"http://www.worldscientific.com/",
"http://www.fairweld.com"]
import urlparse
import requests
import os
for link in links:
r = requests.get(link)
if link.rsrip("/").endswith(".com"):
name = os.path.basename(link)
else:
name = urlparse.urlsplit(link.path.split("/")[-1])
with open("{}.html".format(name),"w") as f:
f.write(r.content)