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返回响应结果。

猜你喜欢

转载自blog.csdn.net/liranke/article/details/113873597