如何获取wget下载的文件的文件名

纳伦德拉乔杜里

os.system('wget '+ link)用来从网站检索文件。下载后,我想根据源链接进一步处理这些文件。

大多数链接都是这种形式htttp://example.com/.../filename.zip
在这种情况下,只需将文件下载为即可filename.zip我既可以使用basenameRegExp也可以从链接中提取内容[^/]+$

但是问题是形式的链接

http://http://www.ez-robot.com
http://www.worldscientific.com/
http://www.fairweld.com

这些链接下载为index.htmlindex.html.1index.html.2ANS等。
在这里,我无法区分哪个index文件属于哪个网站。我这样做的一种方法是查看链接传递到的顺序wget

我想要一些通用方法来获取“真实”文件名,通过该文件名可以在计算机中下载文件。wget执行完毕,它显示终端上的Saving to:标签,其次是“真实”的文件名。我想将该文件名存储在字符串中。

是否有任何直接/简便的方法来获取文件名?我正在使用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
帕德拉克·坎宁安

使用os.path.basename并根据URL的结尾获取名称,您还可以使用请求下载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)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章