urllib库的扩展

一、使用步骤

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"))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值