使用urllib3实现http请求

Urllib3是一个功能强大,条理清晰,用于HTTP客户端的Python库,许多Python的原生系统已经开始使用urllib3。

1.发送请求

import urllib3

# 创建实例
http = urllib3.PoolManager()

#发送请求
rq = http.request('GET', url='http://www.tipdm.com/tipdm/index.html')

2.设置请求头信息

In [ ]:

print('服务器响应码:', rq.status)
print('响应实体:', rq.data)

In [ ]:

import urllib3

http = urllib3.PoolManager()

# 请求头处理
head = {'User-Agent': 'Windows NT 6.1; Win64; x64'}
rq = http.request('GET', url='http://www.tipdm.com/tipdm/index.html', headers=head)

print('服务器响应码:', rq.status)
print('响应实体:', rq.data)

3.防止连接不稳定

In [ ]:

#增加timeout参数设置方法1
import urllib3

http = urllib3.PoolManager()
head = {'User-Agent': 'Windows NT 6.1; Win64; x64'}
#为防止因为网络不稳定、服务器不稳定等问题造成连接不稳定时的丢包,可以在请求中增加timeout参数设置,通常为浮点数。
rq = http.request('GET', url='http://www.tipdm.com/tipdm/index.html', headers=head, timeout=3.0)

print('服务器响应码:', rq.status)
print('响应实体:', rq.data)

In [ ]:

#增加timeout参数设置方法2
import urllib3

http = urllib3.PoolManager()
head = {'User-Agent': 'Windows NT 6.1; Win64; x64'}
rq = http.request('GET', url='http://www.tipdm.com/tipdm/index.html', headers=head,
                  timeout=urllib3.Timeout(connect=1.0, read=2.0))

print('服务器响应码:', rq.status)
print('响应实体:', rq.data)

In [ ]:

#增加timeout参数设置方法3
import urllib3

http = urllib3.PoolManager(timeout=4.0)
head = {'User-Agent': 'Windows NT 6.1; Win64; x64'}
rq = http.request('GET', url='http://www.tipdm.com/tipdm/index.html', headers=head)

print('服务器响应码:', rq.status)
print('响应实体:', rq.data)

4.请求重试设置

In [ ]:

#请求重试设置
import urllib3

http = urllib3.PoolManager(timeout=4.0, retries=10)
head = {'User-Agent': 'Windows NT 6.1; Win64; x64'}
rq = http.request('GET', url='http://www.tipdm.com/tipdm/index.html', headers=head)

print('服务器响应码:', rq.status)
print('响应实体:', rq.data)

In [ ]:

import urllib3

http = urllib3.PoolManager(timeout=4.0)
head = {'User-Agent': 'Windows NT 6.1; Win64; x64'}
rq = http.request('GET', url='http://www.tipdm.com/tipdm/index.html', headers=head, retries=10)

print('服务器响应码:', rq.status)
print('响应实体:', rq.data)

5.完整实例

In [ ]:

import urllib3

# 发送请求实例
http = urllib3.PoolManager()

# 网址
url='http://www.tipdm.com/tipdm/index.html'

# 请求头
head = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36'}
# 超时时间
tm = urllib3.Timeout(connect=1.0, read=3.0)
# 重试次数和重定向次数设置并生成请求
rq = http.request('GET', url=url, headers=head, timeout=tm, retries=5, redirect=4)

print('服务器响应码:', rq.status)
print('响应实体:', rq.data.decode('utf-8'))

6.参考文章

【创作不易,望点赞收藏,若有疑问,请留言,谢谢】

posted @ 2022-07-01 15:28  东血  阅读(646)  评论(0编辑  收藏  举报

载入天数...载入时分秒...