urllib库的基本使用

#urllib库的基本使用
'''
1、网页抓取
就是把URL地址中指定的网络资源从网络流中读取出来,保存到本地。
python2:urllib2
python3:urllib.request
'''

#1、引入模块
from urllib import request


#2、操作
#(1)定义目标url
base_url = "http://www.langlang2017.com/index.html"


#(2)发起请求(GET)--向指定的url发送请求,并返回服务器响应的类文件对象
response = request.urlopen(base_url)

#(3)获取内容
html = response.read()

#(4)转码
html = html.decode('utf-8')

print(html)

#(5)保存内容
with open("langlang2017_index.html","w",encoding="utf-8") as f:
    f.write(html)
原文地址:https://www.cnblogs.com/zhangboblogs/p/8542026.html