首先Urllib是python内置的HTTP请求库。

包括以下模块:

urllib.request 请求模块;

urllib.error 异常处理模块;

urllib.parse url解析模块;

urllib.robotparser robots.txt解析模块。

urllib常规发送请求方式

importurllib.parseimporturllib.request

data= bytes(urllib.parse.urlencode({'word': 'hello'}), encoding='utf8')

response= urllib.request.urlopen('https://httpbin.org/post', data=data)print(response.read())

运行结果:

b'{\n "args": {}, \n "data": "", \n "files": {}, \n "form": {\n "word": "hello"\n }, \n "headers": {\n "Accept-Encoding": "identity", \n "Connection": "close", \n "Content-Length": "10", \n "Content-Type": "application/x-www-form-urlencoded", \n "Host": "httpbin.org", \n "User-Agent": "Python-urllib/3.6"\n }, \n "json": null, \n "origin": "47.74.11.227", \n "url": "https://httpbin.org/post"\n}\n'

需要post数据按指定编码格式编码,在使用urlopen时传递data参数即发送post请求,默认不加就是get请求。

设置超时时间:

importurllib.request

response= urllib.request.urlopen('http://httpbin.org/get', timeout=1)print(response.read())

b'{\n "args": {}, \n "headers": {\n "Accept-Encoding": "identity", \n "Connection": "close", \n "Host": "httpbin.org", \n "User-Agent": "Python-urllib/3.6"\n }, \n "origin": "36.57.169.42", \n "url": "https://httpbin.org/get"\n}\n'

设置超时时间主要是防止爬取某些页面速度极慢,爬的时间过长造成假死状态,从而影响我们的爬虫性能,所以会用到我们的超时时间。

urlopen打开的是什么类型的数据呢,或者是是什么对象。

importurllib.request

response= urllib.request.urlopen('https://www.python.org')print(type(response))

这个对象可以read()方法读取。那么我们都可以读取到那些东西呢。

importurllib.request

response= urllib.request.urlopen('https://www.python.org')print(response.status)print(response.getheaders())print(response.getheader('Server'))

#运行结果#获取状态码

200

#获取请求头的所有信息

[('Server', 'nginx'), ('Content-Type', 'text/html; charset=utf-8'), ('X-Frame-Options', 'SAMEORIGIN'), ('x-xss-protection', '1; mode=block'), ('X-Clacks-Overhead', 'GNU Terry Pratchett'), ('Via', '1.1 varnish'), ('Fastly-Debug-Digest', 'a63ab819df3b185a89db37a59e39f0dd85cf8ee71f54bbb42fae41670ae56fd2'), ('Content-Length', '48907'), ('Accept-Ranges', 'bytes'), ('Date', 'Wed, 31 Jan 2018 11:39:52 GMT'), ('Via', '1.1 varnish'), ('Age', '2396'), ('Connection', 'close'), ('X-Served-By', 'cache-iad2150-IAD, cache-hnd18723-HND'), ('X-Cache', 'HIT, HIT'), ('X-Cache-Hits', '6, 11'), ('X-Timer', 'S1517398792.207858,VS0,VE0'), ('Vary', 'Cookie'), ('Strict-Transport-Security', 'max-age=63072000; includeSubDomains')]#获取服务器

nginx

#获取整个页面的信息

importurllib.request

response= urllib.request.urlopen('https://www.python.org')print(response.read().decode('utf-8'))

在一般情况下我们都需要对请求对象进行改装,加上请求头等信息,这时候我们就要自己定制request对象,然后给他加buff。

from urllib importrequest, parse

url= 'https://httpbin.org/post'headers={'User-Agent': 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)','Host': 'httpbin.org'}

dict={'name': 'Germey'}

data= bytes(parse.urlencode(dict), encoding='utf8')#自定义构造request包含了自定义请求头

req = request.Request(url=url, data=data, headers=headers, method='POST')

response=request.urlopen(req)print(response.read().decode('utf-8'))

{"args": {},"data": "","files": {},"form": {"name": "Germey"},"headers": {"Accept-Encoding": "identity","Connection": "close","Content-Length": "11","Content-Type": "application/x-www-form-urlencoded","Host": "httpbin.org","User-Agent": "Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)"},"json": null,"origin": "36.57.169.42","url": "https://httpbin.org/post"}

另外一种加请求头的方式

from urllib importrequest, parse

url= 'https://httpbin.org/post'dict={'name': 'Germey'}

data= bytes(parse.urlencode(dict), encoding='utf8')

req= request.Request(url=url, data=data, method='POST')

req.add_header('User-Agent', 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)')

response=request.urlopen(req)print(response.read().decode('utf-8'))

结果与上一种请求一定是一模一样的。上面完成了最基本的http请求,如果我们想要完成更高级的http请求,使用代理或者带上cookie值等,那么我们需要使用handler方法,handler有很多种。

importurllib.request#构建一个HTTPHandler处理器对象,支持处理HTTP的请求#http_handler = urllib2.HTTPHandler()

#在HTTPHandler增加参数"debuglevel=1"将会自动打开Debug log 模式,#程序在执行的时候会打印收发包的信息

http_handler = urllib.request.HTTPHandler(debuglevel=1)#调用build_opener()方法构建一个自定义的opener对象,参数是构建的处理器对象

opener =urllib.request.build_opener(http_handler)

request= urllib.request.Request("http://www.baidu.com/")

response=opener.open(request)print(response.read().decode('utf8'))

这里我们定制了一个自己的opener,构建一个Handler处理器对象,参数是一个字典类型,包括代理类型和代理服务器IP+PROT。

importurllib.request#代理开关,表示是否启用代理

proxyswitch =True#proxyswitch = False

#构建一个Handler处理器对象,参数是一个字典类型,包括代理类型和代理服务器IP+PROT

httpproxy_handler = urllib.request.ProxyHandler({"http" : "121.41.175.199:80"})#构建了一个没有代理的处理器对象

nullproxy_handler =urllib.request.ProxyHandler({})ifproxyswitch:

opener=urllib.request.build_opener(httpproxy_handler)else:

opener=urllib.request.build_opener(nullproxy_handler)#构建了一个全局的opener,之后所有的请求都可以用urlopen()方式去发送,也附带Handler的功能

urllib.request.install_opener(opener)

request= urllib.request.Request("http://www.baidu.com/")

response=urllib.request.urlopen(request)#print response.read().decode("gbk")

print(response.read().decode('utf8'))

保存cookie的handler

importhttp.cookiejar, urllib.request

cookie=http.cookiejar.CookieJar()

handler=urllib.request.HTTPCookieProcessor(cookie)

opener=urllib.request.build_opener(handler)

response= opener.open('http://www.baidu.com')for item incookie:print(item.name+"="+item.value)

#将cookie依次打印出来

BAIDUID=185CCA6964D4660F71AC56C5FD40F293:FG=1BIDUPSID=185CCA6964D4660F71AC56C5FD40F293

H_PS_PSSID=25641_1460_24565_21125_18559

PSTM=1517404650BDSVRTM=0

BD_HOME=0

cookie保存成文本文件

importhttp.cookiejar, urllib.request

filename= "cookie.txt"cookie=http.cookiejar.MozillaCookieJar(filename)

handler=urllib.request.HTTPCookieProcessor(cookie)

opener=urllib.request.build_opener(handler)

response= opener.open('http://www.baidu.com')

cookie.save(ignore_discard=True, ignore_expires=True)

将本地的cookie读取出来然后使用本地文本里的cookie去访问网址:

importhttp.cookiejar, urllib.request

cookie=http.cookiejar.LWPCookieJar()

cookie.load('cookie.txt', ignore_discard=True, ignore_expires=True)

handler=urllib.request.HTTPCookieProcessor(cookie)

opener=urllib.request.build_opener(handler)

response= opener.open('http://www.baidu.com')print(response.read().decode('utf-8'))

urlparse将网址分割成多个部分(也可以说是解析)。

from urllib.parse importurlparse

result= urlparse('http://www.baidu.com/index.html;user?id=5#comment')print(type(result), result)

解析的结果:

ParseResult(scheme='http', netloc='www.baidu.com', path='/index.html', params='user', query='id=5', fragment='comment')

#另一种解析

from urllib.parse importurlparse

result= urlparse('www.baidu.com/index.html;user?id=5#comment', scheme='https')print(result)

并且url里的scheme优先级更高。

from urllib.parse importurlparse#url里有scheme,然后我们又传入一次,结果是什么呢

result = urlparse('http://www.baidu.com/index.html;user?id=5#comment', scheme='https')print(result)

#url win

ParseResult(scheme='http', netloc='www.baidu.com', path='/index.html', params='user', query='id=5', fragment='comment')

#不显示什么字段

from urllib.parse importurlparse

result= urlparse('http://www.baidu.com/index.html;user?id=5#comment', allow_fragments=False)print(result)

ParseResult(scheme='http', netloc='www.baidu.com', path='/index.html', params='user', query='id=5#comment', fragment='')

from urllib.parse importurlparse

result= urlparse('http://www.baidu.com/index.html#comment', allow_fragments=False)print(result)

#实际上,这个字段位false那么就减少了一次split,数据还是会存在上一级,但是path之前字段是必须有的

ParseResult(scheme='http', netloc='www.baidu.com', path='/index.html#comment', params='', query='', fragment='')

#反向解析

from urllib.parse importurlunparse

data= ['http', 'www.baidu.com', 'index.html', 'user', 'a=6', 'comment']print(urlunparse(data))#解析结果还原url

http://www.baidu.com/index.html;user?a=6#comment

url拼接

from urllib.parse importurljoinprint(urljoin('http://www.baidu.com', 'FAQ.html'))print(urljoin('http://www.baidu.com', 'https://cuiqingcai.com/FAQ.html'))print(urljoin('http://www.baidu.com/about.html', 'https://cuiqingcai.com/FAQ.html'))print(urljoin('http://www.baidu.com/about.html', 'https://cuiqingcai.com/FAQ.html?question=2'))print(urljoin('http://www.baidu.com?wd=abc', 'https://cuiqingcai.com/index.php'))print(urljoin('http://www.baidu.com', '?category=2#comment'))print(urljoin('www.baidu.com', '?category=2#comment'))print(urljoin('www.baidu.com#comment', '?category=2'))

from urllib.parse importurlencode

params={'name': 'germey','age': 22}

base_url= 'http://www.baidu.com?'url= base_url +urlencode(params)print(url)

http://www.baidu.com?name=germey&age=22

url编码常用于汉字在url中传输时使用。以上就是urllib库常用的操作了。

随着深入的爬虫学习,后面要接触功能强大的Requests库,Requests 唯一的一个非转基因的 Python HTTP 库,人类可以安全享用。

Requests 允许你发送纯天然,植物饲养的 HTTP/1.1 请求,无需手工劳动。你不需要手动为 URL 添加查询字串,也不需要对 POST 数据进行表单编码。Keep-alive 和 HTTP 连接池的功能是 100% 自动化的,一切动力都来自于根植在 Requests 内部的 urllib3。

python中的urllib库_python3里的Urllib库相关推荐

  1. python中goto的用法_python3里用goto

    python里用goto也是小Pa最近做的项目里的一个需求.python不像C有自带的goto, 需要用额外的包,目前为止,小pa只看到2个goto的包: 这2个小Pa都下载试用过,goto因为开发的 ...

  2. python中requests的常用方法_python3 Requests常用操作

    Requests是用Python语言编写的基于urllib,采用Apache2 Licensed开源协议的HTTP库.它比urllib库更加方便.是一个简单易用的HTTP库. 安装pip3 insta ...

  3. python中的def函数括号里的默认值_Python中的默认参数值

    Python对默认参数值的处理方法是少有的几个易使大多数新手Python程序员犯错的地方之一.(通常只犯一次) 导致困惑的地方是当你使用"可变"对象作为(参数的)默认值时的(程序) ...

  4. 用于Python中的进程和系统监视的跨平台库psutil

    最近平台运行,出现一些问题,考虑如何设置监控.发现一个Python库,感觉非常实用.分享一下. psutil(Process and system实用程序)是一个跨平台库,用于检索运行过程和系统利用( ...

  5. python 中的最大堆和最小堆(heapq库)

    目录 首先来看一下什么是最大堆和最小堆? python heapq库中的一些常用方法 小试牛刀 首先来看一下什么是最大堆和最小堆? 最大堆:一种经过排序的完全二叉树,其中任意非终端节点数值均不小于其左 ...

  6. python中max怎么用_python里的max函数怎么用

    python中的max() 方法返回给定参数的最大值,参数可以为序列. 以下是 max() 方法的语法:max( x, y, z, .... ) 参数x -- 数值表达式. y -- 数值表达式. z ...

  7. python3.6安装库_python3.6怎么安装库

    Python3.6安装第三方库有两种方式: 1. 使用 pip 命令行工具在线下载你需要的第三方库 2. 手动下载第三方库,再使用 pip 命令安装 1. 使用 pip 命令行工具在线下载你需要的第三 ...

  8. python中函数包括标准库函数吗_Python标准库(一)

    Hello world, hello everybody! 我是厦门大学王亚南经济研究院2015级的一名本科生,会在项目组专栏不定期更新关于Python标准库的文章. PS. 为了让诸君能够体会徒手敲 ...

  9. Python中非常有用的三个数据科学库

    如果你从事数据科学研究有一段时间了,那么pandas, scikit-learn seaborn和matplotlib这些库你都应该非常的熟悉. 如果您想要扩展您的视野,学习一些更少见但同样有用的库. ...

最新文章

  1. 专治“炼丹侠”各种不服:1分钟就能搞个AI应用 | 最新开源深度学习框架工具套件TinyMS问世...
  2. Node.js 之 新手安装详解 及 npm 配置说明
  3. Token Bucket原理
  4. JavaScript DOM编程艺术(第2版) 笔记
  5. workerman高并发异步mysql_workerman怎么实现高并发
  6. Nature官方劝退读博:全球七成博士对前途迷茫
  7. 分享一个 pycharm 专业版的永久使用方法
  8. 神经网络搭建六步法扩展
  9. 免杀神器-virtest定位特征码
  10. SQL 列转行和动态用时间生数据列
  11. UML--用例图详解
  12. 今日学习在线编程题:可怜的小码哥
  13. 电大计算机专业毕业自我鉴定,广播电视大学毕业自我鉴定3篇
  14. Netty源码解析-Netty内存泄露检测
  15. 哈哈日语 日语五十音图之ら、わ行
  16. 搜索引擎使用的一些基本技巧
  17. 文件上传 黑名单白名单绕过(上)
  18. 爱米云网盘v1.9.4去插件绿色官方版
  19. 干货分享,4款安卓小众软件,每一个都值得保留
  20. Android APP之间共享SharedPreference

热门文章

  1. 流之过滤器流(将过滤器串链在一起)
  2. ASP.net的地址重写(URLRewriter)实现原理及代码示例
  3. TBXML常用API
  4. JavaScript 设计模式核⼼原理与应⽤实践 之 开篇:前端工程师的成长论
  5. 面试官系统精讲Java源码及大厂真题 - 17 并发 List、Map源码面试题
  6. 什么样才能叫精通java_Java学到什么程度才能叫精通?
  7. 【Python】os库的使用
  8. C#LeetCode刷题之#657-机器人能否返回原点(Robot Return to Origin)
  9. chrome关闭自动升级_为什么Chrome的自动完成功能不安全以及如何将其关闭
  10. wordpress忘记登录密码,更改域名的办法。