我正在使用os.system('wget '+ link)
从网站中检索文件。下载后,我想进一步处理这些文件的基础上的源链接。
大多数链接都是这种形式的htttp://example.com/.../filename.zip
。
在这种情况下,文件被简单地下载为filename.zip
。我可以使用basename
和RegExp [^/]+$
从链接中提取这一点。
但问题是表格的链接
http://http://www.ez-robot.com
http://www.worldscientific.com/
http://www.fairweld.com
这些链接被下载为index.html
、index.html.1
、index.html.2
ans等。
在这里,我无法区分哪个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
发布于 2015-04-11 06:37:30
使用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)
发布于 2015-04-11 05:53:14
发生问题的原因是文件名已经存在。我建议下载每一个“文件”到一个新的文件夹(即域名),以防止重复。
$ wget --directory-prefix=$DOMAIN $URL
这将保留数据头中指定的原始文件名。
还有一个提示,您使用的是os.system('wget '+ link)
,它可能非常不安全,因为您在这里没有净化您的输入。输入可能会受到注入的影响,这会使您的系统运行不必要的命令。阅读有关鲍比桌的更多信息。
https://stackoverflow.com/questions/29578439
复制