Python网络编程(二)-使用urllib3进行网络数据请求

1. urllib3简介:

urllib3是python中又一个http请求库。urllib3功能强大,使用简单,已经逐步取代了urllib和urllib2的地位。
urllib3具有如下特点:
线程安全
连接池
SSL/TLS验证
文件分部编码上传
重复请求和HTTP重定位
支持HTTP和SOCKS代理

2. urllib3实例:

使用urllib3获取新浪体育nba网页数据:

python代码如下:

import os
import sys
import urllib3

#检查url地址,如果正确,返回网页内容
def test_urllib3_get(url):
    try:
        http = urllib3.PoolManager()
        r = http.request('GET',url)
        print(r.status)
        #print(r.data)
        return r.data
    except:
        print('无法链接服务器!!!')

#main
if __name__ == '__main__':
    #url='http://sports.sina.com.cn/nba/'
    url="http://www.baidu.com"
    res=test_urllib3_get(url)
    print("test_urllib3_get res:")
    print(res)

运行结果(截取最前面的一小部分):

200

test_urllib3_get res:

b'<!DOCTYPE html><!--STATUS OK-->\r\n<html>\r\n<head>\r\n\t<meta http-equiv="content-type" content="text/html;charset=utf-8">\r\n\t<meta http-equiv="X-UA-Compatible" content="IE=Edge">\r\n\t<link rel="dns-prefetch" href="//s1.bdstatic.com"/>\r\n\t<link rel="dns-prefetch" href="//t1.baidu.com"/>\r\n\t<link rel="dns-prefetch" href="//t2.baidu.com"/>\r\n\t<link rel="dns-prefetch" href="//t3.baidu.com"/>\r\n\t<link rel="dns-prefetch" href="//t10.baidu.com"/>\r\n\t<link rel="dns-prefetch" href="//t11.baidu.com"/>\r\n\t<link rel="dns-prefetch" href="//t12.baidu.com"/>\r\n\t<link rel="dns-prefetch" href="//b1.bdstatic.com"/>\r\n\t<title>\xe7\x99\xbe\xe5\xba\xa6\xe4\xb8\x80\xe4\xb8\x8b\xef\xbc\x8c\xe4\xbd\xa0\xe5\xb0\xb1\xe7\x9f\xa5\xe9\x81\x93</title>\r\n\t<link href="http://s1.bdstatic.com/r/www/cache/static/home/css/index.css" rel="stylesheet" type="text/css" />\r\n\t<!--[if lte IE 8]><style index="index" >#content{height:480px\\9}#m{top:260px\\9}</style><![endif]-->\r\n\t<!--[if IE 8]><style index="index" >#u1 a.mnav,#u1 a.mnav:visited{font-family:simsun}</style><![endif]-->\r\n\t<script>var hashMatch = document.location.href.match(/#+(.*wd=[^&].+)/);if (hashMatch && hashMatch[0] && hashMatch[1]) 

代码说明:

调用PoolManager实例来生成请求,由该实例对象进行真正的数据请求。
通过request()方法创建一个请求,返回一个HTTPResponse对象,将GET,POST和url等作为输入参数。

r.status 和r.data返回响应结果。


urllib3可能是最简单有效的网页数据获取类了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

liranke

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

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

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

打赏作者

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

抵扣说明:

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

余额充值