python中urllib模块

最基本的请求 :是python内置的一个http请求库,不需要额外的安装。只需要关注请求的链接,参数,提供了强大的 解析

  • urllb.request 请求模块
  • urllib.error 异常处理模块
  • urllib.parse 解析模块 用法讲解

简单的一个get请求

import urllib.request
reponse = urllib.request.urlopen('http://www.baidu.com')
print(reponse.read().decode('utf-8'))

简单的一个post请求

import urllib.parse
import urllib.request
data = bytes(urllib.parse.urlencode({'hello':'world'}),encoding='utf-8')
reponse = urllib.request.urlopen('http://httpbin.org/post',data=data)
print(reponse.read())

超时处理

import urllib.request
response = urllib.request.urlopen('http://httpbin.org/get',timeout=1)
print(response.read())
import urllib.request
import socket
import urllib.error
try:
    response = urllib.request.urlopen('http://httpbin.org/get',timeout=0.01)
except urllib.error.URLError as e:
    if isinstance(e.reason,socket.timeout):#判断错误原因
        print('time out!')

打印出响应类型,状态码,响应头

import urllib.request
response=urllib.request.urlopen('http://www.baidu.com')
print(type(response))
import urllib.request
response = urllib.request.urlopen('http://www.baidu.com')
print(response.status) # 状态码 判断请求是否成功
print(response.getheaders()) # 响应头 得到的一个元组组成的列表
print(response.getheader('Server')) #得到特定的响应头
print(response.read().decode('utf-8')) #获取响应体的内容,字节流的数据,需要转成utf-8格式

由于使用urlopen无法传入参数,我们需要解决这个问题 我们需要声明一个request对象,通过这个对象来添加参数

我们可以利用urlopen()方法可以实现最基本请求的发起,但这几个简单的参数并不足以构建一个完整的请求,如果请求中需要加入headers(请求头)等信息,我们就可以利用更强大的Request类来构建一个请求。

import urllib.request
request = urllib.request.Request('https://python.org') #由于urlopen无法传参数,声明一个Request对象
response = urllib.request.urlopen(request)
print(response.read().decode('utf-8'))

我们还可以分别创建字符串、字典等等来带入到request对象里面

from urllib import request,parse
url='http://httpbin.org/post'
headers={
    'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36',
    'Host':'httpbin.org'
}
dict={
    'name':'jay'
}
data = bytes(parse.urlencode(dict),encoding='utf-8')
req=request.Request(url=url,data=data,headers=headers,method='POST')
response=request.urlopen(req)
print(response.read().decode('utf-8'))

我们还可以通过addheaders方法不断的向原始的requests对象里不断添加

from urllib import request,parse

url ='http://httpbin.org/post'
dict = {
    'name':'cq'
}
data=bytes(parse.urlencode(dict),encoding='utf-8')
req = request.Request(url=url,data=data,method='POST')
req.add_header('user-agent', 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36')
response=request.urlopen(req)
print(response.read().decode('utf-8')

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我要努力呀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值