Urllib库:制定URL,获取网页数据,访问url
1、获得get请求
import urllib.request #获取一个get请求 response = urllib.request.urlopen("http://www.baidu.com")#获取网页 print(response.read().decode('utf-8'))#decode('utf-8')解析代码,使中文也可以正常显示
注意:其中这里urlopen,这个函数就是请求一个url的内容,这也是爬虫的第一步:网页请求,获取内容
2、获取post请求
import urllib.parse#解析器 data = bytes(urllib.parse.urlencode({"hello":"world"}),encoding="utf-8") #转化成二进制,封装 response = urllib.request.urlopen("http://httpbin.org/post",data=data) print(response.read().decode('utf-8'))
注意:这里加了data参数就是以POST形式发送请求,否则就是GET方式了。