Python 3.6模块学习urllib的urllib.request.urlopen()函数学习

urllib提供了一系列用于操作URL的功能。包含urllib.request,urllib.error,urllib.parse,urllib.robotparser四个子模块。

官网资料如下:

urllib is a package that collects several modules for working with URLs:

翻译后:
  • urllib.request打开和浏览url中内容 
  • urllib.error包含从 urllib.request发生的错误或异常 
  • urllib.parse解析url 
  • urllib.robotparser解析 robots.txt文件
urllib.request模块中最常用的函数为urllib.request.urlopen()

urllib.request.urlopen函数参数如下:

urllib.request.urlopen(urldata=None[timeout]*cafile=Nonecapath=Nonecadefault=Falsecontext=None)

-         url:  需要打开的网址

-         data:Post提交的数据

-         timeout:设置网站的访问超时时间

urlopen返回对象提供方法:

-         read() , readline() ,readlines() , fileno() , close() :对HTTPResponse类型数据进行操作

-         info():返回HTTPMessage对象,表示远程服务器返回的头信息

-         getcode():返回Http状态码。如果是http请求,200请求成功完成 ; 404网址未找到

-         geturl():返回请求的url


Get

urllib的request模块可以非常方便地抓取URL内容,当data参数为的时候也就是发送一个GET请求到指定的页面,然后返回HTTP的响应:

例如对百度的一个URLhttps://www.baidu.com/进行抓取,并返回响应:

from urllib import request

with request.urlopen('https://www.baidu.com/') as f:
    data = f.read()
    print('Status:', f.status, f.reason)
    print('Data:', data)
运行程序可以得到如下:

Status: 200 OK
Data: b'<html>\r\n<head>\r\n\t<script>\r\n\t\tlocation.replace(location.href.replace("https://","http://"));\r\n\t</script>\r\n</head>\r\n<body>\r\n\t<noscript><meta http-equiv="refresh" content="0;url=http://www.baidu.com/"></noscript>\r\n</body>\r\n</html>

这时我们发现Data内容与网页内容有几分差异

Data的数据格式为bytes类型,需要decode()解码,转换成str类型。

   print('Data:', data.decode('utf-8'))
  把得到的Data变为 utf-8编码形式,变化后如下:
Data: <html>

<head>

	<script>

		location.replace(location.href.replace("https://","http://"));

	</script>

</head>

<body>

	<noscript><meta http-equiv="refresh" content="0;url=http://www.baidu.com/"></noscript>

</body>

</html>
这样得到的内容就可以与网页编码内容一样了

Post

如果要以POST发送一个请求,

urllib.request.urlopen(url,data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None)

urlopen()的data参数默认为None,当data参数不为空的时候,urlopen()提交方式为Post。

Post的数据必须是bytes或者iterable of bytes,不能是str,如果是str需要进行encode()编码

使用Request包装请求

urllib.request.Request(url, data=None, headers={}, method=None)

使用request()来包装请求,再通过urlopen()获取页面。

url= r'http://www.xxxxxxxxxxxxxxxx.com'
headers = {
    'User-Agent': r'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) '
                  r'Chrome/45.0.2454.85 Safari/537.36 115Browser/6.0.3',
    'Referer': r'http://www.xxxxxxxxxxxxxxxx.com',
    'Connection': 'keep-alive'
}
req = request.Request(url, headers=headers)
page = request.urlopen(req).read()
page = page.decode('utf-8')

用来包装头部的数据:

-         User-Agent :这个头部可以携带如下几条信息:浏览器名和版本号、操作系统名和版本号、默认语言

-         Referer:可以用来防止盗链,有一些网站图片显示来源http://***.com,就是检查Referer来鉴定的

-         Connection:表示连接状态,记录Session的状态。



Python官网request库链接





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章