
python爬取网页源代码并存储到本地实例
这里要用到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('blog.csdn/sinat_38052999/article/details/78571416') saveHtml('C:/Users/ASUS/Desktop/text1.html',h) print ("结束")其它方法:
import requests #调用requests库 res = requests.get('knski/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('完成')👁️ 阅读量:0
© 版权声明:本文《python爬取网页源代码并存储到本地实例》内容均为本站精心整理或网友自愿分享,如需转载请注明原文出处:https://www.zastudy.cn/wen/1686621098a307758.html。