这周打算把学过的内容重新总结一下,便于以后翻阅查找资料。

urllib库是python的内置库,不需要单独下载。其主要分为四个模块:

1.urllib.request——请求模块

2.urllib.error——异常处理模块

3.urllib.parse——url解析模块

4.urllib.robotparser——用来识别网站的robot.txt文件(看看哪些内容是可以爬的,不常用)

1.urlopen

  1. import urllib.request
  2.  
  3. response = urllib.request.urlopen('http://www.baidu.com')
  4. print(response.read().decode('utf-8'))
  1. 超时读取
  2. import socket
  3. import urllib.request
  4. import urllib.error
  5.  
  6. try:
  7. response = urllib.request.urlopen('http://httpbin.org/get', timeout=0.1)
  8. except urllib.error.URLError as e:
  9. if isinstance(e.reason, socket.timeout):
  10. print('TIME OUT')
  1. 响应内容分析
  2. import urllib.request
  3.  
  4. response = urllib.request.urlopen('https://www.python.org')
  5. print(type(response))
  6. print(response.status)
  7. print(response.getheaders())
  8. print(response.getheader('Server'))
  1. <class 'http.client.HTTPResponse'>
  2. 200
  3. [('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'), ('Content-Length', '50069'), ('Accept-Ranges', 'bytes'), ('Date', 'Mon, 26 Nov 2018 02:44:49 GMT'), ('Via', '1.1 varnish'), ('Age', '3121'), ('Connection', 'close'), ('X-Served-By', 'cache-iad2150-IAD, cache-sjc3143-SJC'), ('X-Cache', 'MISS, HIT'), ('X-Cache-Hits', '0, 254'), ('X-Timer', 'S1543200290.644687,VS0,VE0'), ('Vary', 'Cookie'), ('Strict-Transport-Security', 'max-age=63072000; includeSubDomains')]
  4. nginx

2. request

  1. 用来传递更多的请求参数,url,headers,data, method
  2. from urllib import request, parse
  3.  
  4. url = 'http://httpbin.org/post'
  5. headers = {
  6. 'User-Agent': 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)',
  7. 'Host': 'httpbin.org'
  8. }
  9. dict = {
  10. 'name': 'Germey'
  11. }
  12. data = bytes(parse.urlencode(dict), encoding='utf8')
  13. req = request.Request(url=url, data=data, headers=headers, method='POST')
  14. response = request.urlopen(req)
  15. print(response.read().decode('utf-8'))
  1. {
  2. "args": {},
  3. "data": "",
  4. "files": {},
  5. "form": {
  6. "name": "Germey"
  7. },
  8. "headers": {
  9. "Accept-Encoding": "identity",
  10. "Connection": "close",
  11. "Content-Length": "11",
  12. "Content-Type": "application/x-www-form-urlencoded",
  13. "Host": "httpbin.org",
  14. "User-Agent": "Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)"
  15. },
  16. "json": null,
  17. "origin": "117.136.66.101",
  18. "url": "http://httpbin.org/post"
  19. }
  1. 另一种方法添加headers
  2.  
  3. from urllib import request, parse
  4.  
  5. url = 'http://httpbin.org/post'
  6. dict = {
  7. 'name': 'asd'
  8. }
  9. data = bytes(parse.urlencode(dict), encoding='utf8')
  10. req = request.Request(url=url, data=data, method='POST')
  11. req.add_header('User-Agent', 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)') #如果有好多headers,可以循环添加
  12. response = request.urlopen(req)
  13. print(response.read().decode('utf-8'))

3. Handler

  1. 代理
  2. import urllib.request
  3.  
  4. proxy_handler = urllib.request.ProxyHandler({
  5. 'http': 'http://127.0.0.1:9743',
  6. 'https': 'https://127.0.0.1:9743'
  7. })
  8. opener = urllib.request.build_opener(proxy_handler)
  9. response = opener.open('https://www.httpbin,org/get')
  10. print(response.read())

4. Cookie

  1. 获取cookie
    import http.cookiejar, urllib.request
  2.  
  3. cookie = http.cookiejar.CookieJar()
  4. handler = urllib.request.HTTPCookieProcessor(cookie)
  5. opener = urllib.request.build_opener(handler)
  6. response = opener.open('http://www.baidu.com')
  7. for item in cookie:
  8. print(item.name+"="+item.value)
  1. 存储Cookie
  2. import http.cookiejar, urllib.request
  3. filename = "cookie.txt"
  4. cookie = http.cookiejar.MozillaCookieJar(filename)
  5. handler = urllib.request.HTTPCookieProcessor(cookie)
  6. opener = urllib.request.build_opener(handler)
  7. response = opener.open('http://www.baidu.com')
  8. cookie.save(ignore_discard=True, ignore_expires=True)
  1. 获取Cookie
  2. import http.cookiejar, urllib.request
  3. cookie = http.cookiejar.MozillaCookieJar()
  4. cookie.load('cookie.txt', ignore_discard=True, ignore_expires=True)
  5. handler = urllib.request.HTTPCookieProcessor(cookie)
  6. opener = urllib.request.build_opener(handler)
  7. response = opener.open('http://www.baidu.com')
  8. print(response.read().decode('utf-8'))

5. UrlError 和 HttpError

  1. from urllib import request, error
  2.  
  3. try:
  4. response = request.urlopen('http://cuiqingcai.com/index.htm')
  5. except error.HTTPError as e:
  6. print(e.reason, e.code, e.headers, sep='\n')
  7. except error.URLError as e:
  8. print(e.reason)
  9. else:
  10. print('Request Successfully')

对于urllib.parse,因为用的不多,就先不写了。上传一个文档链接吧,万一哪天用了还可以看看。

https://files.cnblogs.com/files/zhangguoxv/urllib%E8%AE%B2%E8%A7%A3.zip

urllib库使用方法的更多相关文章

  1. urllib库使用方法 4 create headers

    import urllib.requestimport urllib.parse url = "https://www.baidu.com/"#普通请求方法response = u ...

  2. urllib库使用方法 3 get html

    import urllib.requestimport urllib.parse #https://www.baidu.com/s?ie=UTF-8&wd=中国#将上面的中国部分内容,可以动态 ...

  3. urllib库使用方法 2 parse

    import urllib.parse #url.parse用法包含三个方法:quote url, unquote rul, urlencode#quote url 编码函数,url规范只识别字母.数 ...

  4. urllib库使用方法1 request

    urllib是可以模仿浏览器发送请求的库,Python自带 Python3中urllib分为:urllib.request和urllib.parse import urllib.request url ...

  5. Python爬虫学习==>第七章:urllib库的基本使用方法

    学习目的: urllib提供了url解析函数,所以需要学习正式步骤 Step1:什么是urllib urllib库是Python自带模块,是Python内置的HTTP请求库 包含4个模块: >& ...

  6. python--爬虫入门(七)urllib库初体验以及中文编码问题的探讨

    python系列均基于python3.4环境 ---------@_@? --------------------------------------------------------------- ...

  7. urllib库初体验以及中文编码问题的探讨

    提出问题:如何简单抓取一个网页的源码 解决方法:利用urllib库,抓取一个网页的源代码 ------------------------------------------------------- ...

  8. Python爬虫入门 Urllib库的基本使用

    1.分分钟扒一个网页下来 怎样扒网页呢?其实就是根据URL来获取它的网页信息,虽然我们在浏览器中看到的是一幅幅优美的画面,但是其实是由浏览器解释才呈现出来的,实质它是一段HTML代码,加 JS.CSS ...

  9. Python爬虫入门:Urllib库的基本使用

    1.分分钟扒一个网页下来 怎样扒网页呢?其实就是根据URL来获取它的网页信息,虽然我们在浏览器中看到的是一幅幅优美的画面,但是其实是由浏览器解释才呈现出来的,实质它 是一段HTML代码,加 JS.CS ...

随机推荐

  1. Java实现 LeetCode 803 打砖块 (DFS)

    803. 打砖块 我们有一组包含1和0的网格:其中1表示砖块. 当且仅当一块砖直接连接到网格的顶部,或者它至少有一块相邻(4 个方向之一)砖块不会掉落时,它才不会落下. 我们会依次消除一些砖块.每当我 ...

  2. Java实现蓝桥杯VIP算法训练 自行车停放

    试题 算法训练 自行车停放 资源限制 时间限制:1.0s 内存限制:256.0MB 问题描述 有n辆自行车依次来到停车棚,除了第一辆自行车外,每辆自行车都会恰好停放在已经在停车棚里的某辆自行车的左边或 ...

  3. 类似-Xms、-Xmn这些参数的含义:

    类似-Xms.-Xmn这些参数的含义: 答: 堆内存分配: JVM初始分配的内存由-Xms指定,默认是物理内存的1/64 JVM最大分配的内存由-Xmx指定,默认是物理内存的1/4 默认空余堆内存小于 ...

  4. java实现第四届蓝桥杯错误票据

    错误票据 题目描述 某涉密单位下发了某种票据,并要在年终全部收回. 每张票据有唯一的ID号.全年所有票据的ID号是连续的,但ID的开始数码是随机选定的. 因为工作人员疏忽,在录入ID号的时候发生了一处 ...

  5. java代码(15) ---java8 Function 、Consumer 、Supplier

    Java8 Function.Consumer.Supplier 有关JDK8新特性之前还有三篇博客: 1,java代码(1)---Java8 Lambda 2,java代码(2)---Java8 S ...

  6. Linux用户管理命令useradd、passwd、who详解

    创建用户命令useradd 命令useradd,所在路径为: 可以看到命令useradd的路径为:/usr/sbin/useradd,因此它的执行权限是root 命令的功能是创建一个新用户,例如:us ...

  7. Java多线程之深入解析ThreadLocal和ThreadLocalMap

    ThreadLocal概述 ThreadLocal是线程变量,ThreadLocal中填充的变量属于当前线程,该变量对其他线程而言是隔离的.ThreadLocal为变量在每个线程中都创建了一个副本,那 ...

  8. 创建sudo -i免密权限账户

    项目原因,服务器需要创建普通用户,但又不能让用户拿到root密码. 创建用户 [root@bogon ~]# groupadd connect [root@bogon ~]# useradd -g c ...

  9. HDU - 3591 The trouble of Xiaoqian 题解

    题目大意 有 \(N\) 种不同面值的硬币,分别给出每种硬币的面值 \(v_i\) 和数量 \(c_i\).同时,售货员每种硬币数量都是无限的,用来找零. 要买价格为 \(T\) 的商品,求在交易中最 ...

  10. 查询局域网指定段内存活IP

    目录 批量ping 输出到指定文件 批量ping for /L %i IN (起始,扫描间距,结束) DO ping -w 2 -n 1 10.224.131.%i 如 for /L %i IN (5 ...