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

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

1.urllib.request——请求模块

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

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

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

1.urlopen

import urllib.request

response = urllib.request.urlopen('http://www.baidu.com')
print(response.read().decode('utf-8'))
超时读取
import socket
import urllib.request
import urllib.error try:
response = urllib.request.urlopen('http://httpbin.org/get', timeout=0.1)
except urllib.error.URLError as e:
if isinstance(e.reason, socket.timeout):
print('TIME OUT')
响应内容分析
import urllib.request response = urllib.request.urlopen('https://www.python.org')
print(type(response))
print(response.status)
print(response.getheaders())
print(response.getheader('Server'))
<class 'http.client.HTTPResponse'>
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'), ('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')]
nginx

2. request

用来传递更多的请求参数,url,headers,data, method
from urllib import request, parse url = 'http://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')
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": "117.136.66.101",
"url": "http://httpbin.org/post"
}
另一种方法添加headers

from urllib import request, parse

url = 'http://httpbin.org/post'
dict = {
'name': 'asd'
}
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)') #如果有好多headers,可以循环添加
response = request.urlopen(req)
print(response.read().decode('utf-8'))

3. Handler

代理
import urllib.request proxy_handler = urllib.request.ProxyHandler({
'http': 'http://127.0.0.1:9743',
'https': 'https://127.0.0.1:9743'
})
opener = urllib.request.build_opener(proxy_handler)
response = opener.open('https://www.httpbin,org/get')
print(response.read())

4. Cookie

获取cookie
import http.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 in cookie:
print(item.name+"="+item.value)
存储Cookie
import http.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
import http.cookiejar, urllib.request
cookie = http.cookiejar.MozillaCookieJar()
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'))

5. UrlError 和 HttpError

from urllib import request, error

try:
response = request.urlopen('http://cuiqingcai.com/index.htm')
except error.HTTPError as e:
print(e.reason, e.code, e.headers, sep='\n')
except error.URLError as e:
print(e.reason)
else:
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 806 写字符串需要的行数 (暴力模拟)

    806. 写字符串需要的行数 我们要把给定的字符串 S 从左到右写到每一行上,每一行的最大宽度为100个单位,如果我们在写某个字母的时候会使这行超过了100 个单位,那么我们应该把这个字母写到下一行. ...

  2. Java实现 蓝桥杯 算法提高 欧拉函数(数学)

    试题 算法提高 欧拉函数 问题描述 老师出了一道难题,小酱不会做,请你编个程序帮帮他,奖金一瓶酱油: 从1-n中有多少个数与n互质? |||||╭══╮ ┌═════┐ ╭╯让路║═║酱油专用车║ ╰ ...

  3. Java实现最大流量问题

    1 问题描述 何为最大流量问题? 给定一个有向图,并为每一个顶点设定编号为0~n,现在求取从顶点0(PS:也可以称为源点)到顶点n(PS:也可以称为汇点)后,顶点n能够接收的最大流量.图中每条边的权值 ...

  4. java实现拍7游戏

    ** 拍7游戏** 许多人都曾经玩过"拍七"游戏.规则是:大家依次从1开始顺序数数,数到含有7或7的倍数的要拍手或其它规定的方式表示越过(比如:7,14,17等都不能数出),下一人 ...

  5. Java 实现 蓝桥杯 历届试题 分糖果

    问题描述 有n个小朋友围坐成一圈.老师给每个小朋友随机发偶数个糖果,然后进行下面的游戏: 每个小朋友都把自己的糖果分一半给左手边的孩子. 一轮分糖后,拥有奇数颗糖的孩子由老师补给1个糖果,从而变成偶数 ...

  6. (十)DVWA之SQL Injection--测试分析(Impossible)

    DVWA之SQL Injection--测试分析(Impossible) 防御级别为Impossible的后端代码:impossible.php <?php if( isset( $_GET[ ...

  7. 【原创】Linux中断子系统(二)-通用框架处理

    背景 Read the fucking source code! --By 鲁迅 A picture is worth a thousand words. --By 高尔基 说明: Kernel版本: ...

  8. 【Spring注解驱动开发】组件注册-@ComponentScan-自动扫描组件&指定扫描规则

    写在前面 在实际项目中,我们更多的是使用Spring的包扫描功能对项目中的包进行扫描,凡是在指定的包或子包中的类上标注了@Repository.@Service.@Controller.@Compon ...

  9. Android事件传递机制总结

    Android中控件的分类 Activity dispatchTouchEvent(MotionEvent e) onTouchEvent(MotionEvent e) ViewGroup(View) ...

  10. 3.vue计算属性

    1.计算属性  再vue中如果出现表达式过长或者逻辑比较复杂,这时会导致代码不清晰,臃肿,难以维护所以我们会使用计算属性进行书写  再计算属性中可以放负责的逻辑,可以是函数,表达式等,但最终会返回一个 ...