使用python将某些网站的HTML保存在txt文件中
发布时间:2020-12-16 23:17:45 所属栏目:Python 来源:网络整理
导读:我需要在txt文件中保存任何网站的 HTML代码,这是一个非常简单的练习,但我对此有疑问,因为有一个函数可以做到这一点: import urllib.requestdef get_html(url): f=open('htmlcode.txt','w') page=urllib.request.urlopen(url) pagetext=page.read() ## Save
我需要在txt文件中保存任何网站的
HTML代码,这是一个非常简单的练习,但我对此有疑问,因为有一个函数可以做到这一点:
import urllib.request def get_html(url): f=open('htmlcode.txt','w') page=urllib.request.urlopen(url) pagetext=page.read() ## Save the html and later save in the file f.write(pagetext) f.close() 但这不起作用. 解决方法
最简单的方法是使用
urlretrieve:
import urllib urllib.urlretrieve("http://www.example.com/test.html","test.txt") 对于Python 3.x,代码如下: import urllib.request urllib.request.urlretrieve("http://www.example.com/test.html","test.txt") (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |