注意,导包时候要导入urllib.request,只导urllib可能会报错
import urllib.request
#get请求
rep = urllib.request.urlopen("http://www.baidu.com")
print(rep.read().decode("utf_8"))
#post请求
a = bytes(urllib.parse.urlencode({}),encoding="utf-8")
rsp = urllib.request.urlopen("http://httpbin.org/post",data=a )
print(rsp.read().decode('utf-8'))
#增加headers的post请求
url="http://httpbin.org/post"
a = bytes(urllib.parse.urlencode({}),encoding="utf-8")
header = {"User-Agent":" Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.93 Safari/537.36"}
req = urllib.request.Request(url=url,data=a,headers=header)
rsp = urllib.request.urlopen(req)
print(rsp.read().decode('utf-8'))