我想将整个项目从cdnjs云下载到本地文件夹。我已经试过了:
import requests
files = requests.get("https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-AMS-MML_HTMLorMML%2CSafe.js&ver=4.1")
with open("mathjax.js","w") as file:
file.write(files.text)
现在下载js文件。当我尝试使用相同的代码而不是js文件获取项目时,输出结果很奇怪。
因此,我尝试使用cdnjs并检查使用cdnjs云和使用本地文件时会发生什么。
我有如图所示的这种区别:
如何获得与使用cdnjs时类似的结构?请告诉我。
MathJax.js
的URL,这就是为什么只获得该文件作为输出的原因。您需要下载完整目录mathjax/2.7.5/
。但是,如果我们请求整个目录,服务器将禁止此类请求。 一种替代方法是从主目录中获取所有文件的相对路径,如图所示,该目录已经具有。然后,您可以独立下载每个文件,并将其存储到其各自的文件夹中。您将在最后准备好整个目录。
为此尝试以下代码。
import requests
import os
baseUrl="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5" #Base URL for the main directory
#List containing relative paths of all required files
relativePaths=['config/Safe.js?V=2.7.5',
'config/TeX-AMS-MML_HTMLorMML.js?V=2.7.5',
'extensions/Safe.js?V=2.7.5',
'jax/output/SVG/fonts/TeX/fontdata.js?V=2.7.5',
'jax/output/SVG/jax.js?V=2.7.5',
'MathJax.js?config=TeX-AMS-MML_HTMLorMML%2CSafe.js&ver=4.1']
parentDir='\\'.join(baseUrl.split('/')[-2:]) #Parent directory from URL
for path in relativePaths: #For all files
req=requests.get(baseUrl+path) #forming url
filename=path.split("/")[-1].split("?")[0] #extracting filename out of url
directory=os.path.join(parentDir,"\\".join(path.split('/')[:-1])) #Extracting directories path for local path formation
if not os.path.exists(directory): #Creating local direcories if they do not exist
os.makedirs(directory)
with open(os.path.join(directory,filename),"wb+") as file: #Storing results into files
file.write(req.content)
本地目录结构输出:
import requests
url = 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-AMS-MML_HTMLorMML%2CSafe.js&ver=4.1'
files = requests.get(url)
我建议您在file mode中使用写入和二进制(wb)。然后,只需要编写请求的二进制内容即可。
with open('mathjax.js', 'wb') as r: r.write(files.content)
那是您最终应该拥有的
import requests url = 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-AMS-MML_HTMLorMML%2CSafe.js&ver=4.1' files = requests.get(url) with open('mathjax.js', 'wb') as r: r.write(files.content)