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

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实现 蓝桥杯VIP 算法训练 步与血(递推 || DFS)

    试题 算法训练 步与血 问题描述 有n*n的方格,其中有m个障碍,第i个障碍会消耗你p[i]点血.初始你有C点血,你需要从(1,1)到(n,n),并保证血量大于0,求最小步数. 输入格式 第一行3个整 ...

  2. Java实现 蓝桥杯 算法提高 日期计算

    算法提高 日期计算 时间限制:1.0s 内存限制:256.0MB 问题描述 已知2011年11月11日是星期五,问YYYY年MM月DD日是星期几?注意考虑闰年的情况.尤其是逢百年不闰,逢400年闰的情 ...

  3. Java实现 蓝桥杯VIP 算法训练 采油区域

    算法训练 采油区域 时间限制:2.0s 内存限制:512.0MB 提交此题 查看参考代码 采油区域 Siruseri政府决定将石油资源丰富的Navalur省的土地拍卖给私人承包商以建立油井.被拍卖的整 ...

  4. 为什么我觉得 Java 的 IO 很复杂?

    初学者觉得复杂是很正常的,归根结底是因为没有理解JavaIO框架的设计思想: 可以沿着这条路想一想: 1,学IO流之前,我们写的程序,都是在内存里自己跟自己玩.比如,你声明个变量,创建个数组,创建个集 ...

  5. 哪些年,我们玩过的Git

    作者:玩世不恭的Coder公众号:玩世不恭的Coder时间:2020-06-05说明:本文为原创文章,未经允许不可转载,转载前请联系作者 哪些年,我们玩过的Git 前言一.前期工作常用基本概念的理解G ...

  6. (十一)DVWA全等级SQL Injection(Blind)盲注--手工测试过程解析

    一.DVWA-SQL Injection(Blind)测试分析 SQL盲注 VS 普通SQL注入: 普通SQL注入 SQL盲注 1.执行SQL注入攻击时,服务器会响应来自数据库服务器的错误信息,信息提 ...

  7. 4.keras-交叉熵的介绍和应用

    keras-交叉熵的介绍和应用 1.载入数据以及预处理 import numpy as np from keras.datasets import mnist from keras.utils imp ...

  8. AsyncTask源码解读

    AsyncTask源码解读 一.基本使用 protected void onPreExecute() protected abstract Result doInBackground(Params.. ...

  9. 分布式数据库PolonDB 云端发力未来数据处理需求

    企业数字化转型的不断深入,传统 IT 架构和数据库早已无法适应诸如物联网.新金融.新零售.新制造等行业对于数据高吞吐.灵活扩展等需求,企业对数据库有了更高的要求. 青云QingCloud 本次推出的 ...

  10. Python大神编程常用4大工具,你用过几个?

    摘要:Python是一种跨平台的编程语言,能够在所有主要的操作系统上,运行你编写的任何Python程序.今天介绍几款常见的工具:Python自带的解释器.文本编辑器(Geany.Sublime Tex ...