Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 如何将网站的源代码保存在.txt文件中?_Python 3.x - Fatal编程技术网

Python 3.x 如何将网站的源代码保存在.txt文件中?

Python 3.x 如何将网站的源代码保存在.txt文件中?,python-3.x,Python 3.x,如何将任何网站的源代码保存在.txt文件中? 我使用的是python版本3关于这一点有很多视频和教程,但仍然: url = "http://" + str(input) t = urllib.request.urlopen(url) 您可以通过多种方式完成此任务 步骤1:获取数据 这可以使用您选择的任何库来完成,我个人最喜欢的是请求,代码如下 import urllib t = urllib.urlopen(url).read() with open("c:\\source_code.tx

如何将任何网站的源代码保存在.txt文件中?
我使用的是python版本3

关于这一点有很多视频和教程,但仍然:

url = "http://" + str(input)
t = urllib.request.urlopen(url)

您可以通过多种方式完成此任务

步骤1:获取数据 这可以使用您选择的任何库来完成,我个人最喜欢的是请求,代码如下

import urllib

t = urllib.urlopen(url).read()

with open("c:\\source_code.txt",'w') as source_code:
    source_code.write(t)
此代码将对象存储在一个位置,以获取您可以使用的文本格式的数据

import requests
headers = {'User-agents':'Mozilla/5.0'}
html_data = requests.get('Your url goes here',headers=headers)
步骤2:将此数据保存到本地计算机上的文本文件中 这会将网站中的所有html代码保存到路径中提到的文本文件中

如果您明确表示要在网站中保存可见数据,请尝试使用一些解析器库,我建议使用BeautifulSoup

下面是指向所使用和推荐的库的实际python文档的链接

  • Lib-请求-
  • Lib-美丽群-

    • 这是最快的方法:

      file = open('your file path goes here','ab') //this will open the file you have specified in the path
      file.write(html.text.encode('UTF-8')) //Most of the HTML pages are encoded in ascii, you need to convert it into 'UTF-8' encoding to write it into a txt file.
      file.close() //Close the file. all the mishaps in the world will happen if you don't close the file which is opened
      

      请记住,站点可能并不总是
      http://
      ,并且
      input()
      总是使用
      ()

      查看此处:它显示错误:必须是str,而不是字节。我不知道这是什么意思。
      file = open('your file path goes here','ab') //this will open the file you have specified in the path
      file.write(html.text.encode('UTF-8')) //Most of the HTML pages are encoded in ascii, you need to convert it into 'UTF-8' encoding to write it into a txt file.
      file.close() //Close the file. all the mishaps in the world will happen if you don't close the file which is opened
      
      import urllib.request
      a = str(input())
      url = "http://" + a
      urllib.request.urlretrieve(url, 'page.txt')