admin管理员组

文章数量:1794759

python爬取网页源代码并存储到本地实例

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('完成')

本文标签: 源代码实例网页Python