一、使用步骤
1.引入库
代码如下(示例):
import urllib.request
2.读入数据
代码如下(示例):
#获取一个get请求
reponse=urllib.request.urlopen("http://www.baidu.com")#response 保存了网页里所有保存的信息
reponse.read().decode('utf-8') #把读到的信息用UTF-8来解码,用来防乱码
#获取一个post请求:post需要进行封装成二进制,才能进行数据的传输
import urllib.parse
data=byte(urllib.parse.urlencode({"hello":"world"}),encoding="utf-8")
reponse=urllib.request.urlopen("http://httpbin.prg/post",data=_data)
print(response.read().decode("utf-8"))
#超时问题
try:
reponse=urllib.request.urlopen("http://httpbin.prg/get",timeout=0.01)
print(response.read().decode("utf-8"))
except urllib.error.URLError as e:
print("time out!")
#响应头问题
reponse=urllib.request.urlopen("http://httpbin.prg/get")
response.status() #返回状态码
reponse.getheader("Sever") #用来访问响应头中的Sever信息
#进行访问头伪装
url="https://www.douban.com"
headers={
#输入响应的浏览器的 User-Agent 信息
}
#用head对req进行封装
req=urllib.request.Request(url=url,data=data,headers=headers,method="Post")
response=urllib.request.urlopen(req)
print(response.read().decode("utf-8"))