我想下载所有以.qrs、.dat、.hea结尾的文件,并将它们存储在本网站的本地文件夹中。在
https://physionet.org/physiobank/database/shareedb/
我尝试从下面的链接修改解决方案。在
我是这样修改代码的:
import os
from bs4 import BeautifulSoup
# Python 3.x
from urllib.request import urlopen, urlretrieve
URL = 'https://physionet.org/physiobank/database/shareedb/'
OUTPUT_DIR = '' # path to output folder, '.' or '' uses current folder
u = urlopen(URL)
try:
html = u.read().decode('utf-8')
finally:
u.close()
soup = BeautifulSoup(html, "html.parser")
for link in soup.select('a[href^="https://"]'): # or a[href*="shareedb/0"]
href = link.get('href')
if not any(href.endswith(x) for x in ['.dat','.hea','.qrs']):
continue
filename = os.path.join(OUTPUT_DIR, href.rsplit('/', 1)[-1])
# We need a https:// URL for this site
# href = href.replace('http://','https://')
print("Downloading %s to %s..." % (href, filename) )
urlretrieve(href, filename)
print("Done.")
当我运行这段代码时,它不会从目标页面中提取文件,也不会输出任何失败消息(例如“failed to download”)。在
经过一些调试后,我发现在我的例子中没有文件被选中。我怀疑它与html的结构有关。在
如何使用Python将这些文件下载到本地目录?在
为了扩展wolf tian的答案,select没有找到任何内容,因为该站点中的链接在其href中没有
"https://"
(也没有"shareedb"
)。您试图下载的文件都具有<a href="01911.hea">01911.hea</a>
的结构。他们的路径是相对的。因此,您需要首先提取这些文件名,例如:然后,您需要在检索URL之前将主机部分应用于该URL:
^{pr2}$您可以使用优秀的^{} 库,如下所示:
这将把所有
.dat
、.hea
和.qrs
文件下载到您的计算机上。在使用标准安装:
^{pr2}$注意,该URL上的所有href格式都适合直接用作文件名(因此目前不需要解析任何
/
字符)。在输出:
^{pr2}$相关问题 更多 >
编程相关推荐