这里要用到urllib库
所以首先要安装库
1、windows+r
2、cmd
3、pip install urllib
4、运行下面代码
5、存储完成后,就可以在没有联网的情况下,也能在本地打开该网页
import urllib.request
def getHtml(url):
h = urllib.request.urlopen(url).read()
return h
def saveHtml(file_name,file_content):
# 注意windows文件命名的禁用符,比如 /
with open (file_name,"wb") as f:
# 写文件用bytes而不是str,所以要转码
f.write( file_content )
h=getHtml('https://blog.csdn.net/sinat_38052999/article/details/78571416')
saveHtml('C:/Users/ASUS/Desktop/text1.html',h)
print ("结束")
其它方法:
import requests #调用requests库
res = requests.get('https://kns.cnki.net/KCMS/detail/50.1044.N.20200619.1019.002.html')
#获取网页源代码,得到的res是Response对象
html = res.text #字符串
html = html.encode() #把str转化成byte
with open('C:/Users/ASUS/Desktop/wenjian.html','wb') as f:
f.write(html)
f.close()
print('完成')
本文介绍如何利用Python的urllib和requests库将指定URL的网页内容下载并保存到本地,实现离线浏览。通过具体示例代码,读者可以学习到如何处理文件命名中的非法字符,以及如何将网页源代码从str类型转换为byte类型进行存储。
4066

被折叠的 条评论
为什么被折叠?



