下载 xml- 文件并将其保存到文本文件

Download xml-file and save it to a text file

我是编程新手,遇到了问题。我需要创建一个 Python 函数,该函数使用请求外部模块下载 XML 文件,然后将响应文本保存到文本文件中。

到目前为止我试过这个:

import requests
def downloading_xml():
   r = requests.get('https://www.w3schools.com/xml/simplexsl.xml')
   print(r.text)

但我不太明白。我认为我的主要问题是最后一部分,我不知道如何将响应文本保存到文本文件中。有任何想法吗?提前致谢!

要保存到文本文件,您可以这样做:

textfile=open("anyname.xml",'w')
textfile.write(r.text)
textfile.close()

您可能还需要包含文件的路径

给你。如果您想了解更多关于 Python 文件操作的信息,请关注此 link Python I/O

import requests
def downloading_xml():
  r = requests.get('https://www.w3schools.com/xml/simplexsl.xml')
  print(r.text)
  with open("filename.txt", "w+") as f:
    f.write(r.text)
    f.close()

现在调用函数

downloading_xml()