了解即可,不好用
 

一. 概述

 
python内置的http请求库,包括4个模块,分别如下
 
urllib.request   请求模块
urllib.error       异常处理模块
urllib.parse      url解析模块, 工具模块
urllib.robotparser    robots.txt解析模块
 
 
 
urlopen
python2和python3中urlopen方法的不同用法
 
python2中
import urllib2
response=urllib2.urlopen('http://www.baidu.com')
 
python3中
import urllib.request
response=urllib.request.urlopen('http://www.baidu.com')
 

二. urlopen用法

 
1. 获取普通源代码,get方法
import urllib.request

response=urllib.request.urlopen('http://www.baidu.com')
print(response.read().decode('utf-8')
2. post方法请求,传入一个字典
import urllib.parse
import urllib.request data=bytes(urllib.parse.urlencode({'word':'hello'}), encoding='utf8') //传入一个值
response=urllib.request.urlopen('http://httpbin.org/post', data=data)
print(response.read())
3. 超时操作,在指定时间内未得到响应就抛出异常
import urllib.request

response = urllib.request.urlopen('http://httpbin.org/get', timeout=1)
print(response.read())
 
4. 查看异常
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')
 
 

三. 响应

 
1. 响应类型
import urllib.request

response = urllib.request.urlopen('https://www.python.org')
print(type(response))
 
2. 状态码,响应头
import urllib.request

response = urllib.request.urlopen('https://www.python.org')
print(response.status)
print(response.getheaders()) //数组的形式,每个数组元素都是一个元组
print(response.getheader('Server')) //获取数组元素中元组键名为Server的值
 
3. Request()方法单独使用来请求页面
 
import urllib.request

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

可以在请求中加入头信息等数据
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.Requests(url=url, data=data, headers=headers, method='POST')
response = request.urlopen(req)
print(response.read().decode('utf-8'))
 
 

使用add_header()方法来添加header
 
from urllib import request, parse

url = 'http://httpdbin.org/post'
dict = {
'name': 'Germey'
}
data = bytes(parse.urlencode(dict), encoding='utf8')
req = request.Requests(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'))
 
 
 

4. Handler

 
1. 代理
 
import urllib.request

proxy_handler = urllib.request.ProxyHander({
'http':'http://127.0.0.1:9743'
'https':'https://127.0.0.1:9743'
})
opener = urllib.requets.build_opener(proxy_handler)
response = opener.open('http://www.baidu.com')
print(response.read())
 
 
2. Cookie
 
例子1,打印出cookie信息
import http.cookiejar,urlib.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)
 
例子2,保存cookie信息到文本文件
import http.cookiejar, urllib.requst
filename = 'cookie.txt'
cookie = http.cookiejar.MozillaCookieJar(filename)
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.requst.build_opener(handler)
response = opener.open('http://www.baidu.com')
cookie.save(ignore_discard=True, ignore_expires=True)
 
 
例子3,另外一种保存方法
import http.cookiejar, urllib.request
filename = 'cookie.txt'
cookie = http.cookiejar.LWPCookieJar(filename)
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(hander)
response = opener.open('http://www.baidu.com')
cookie.save(ignore_discard=True, ignore_expires=True)
 
 
例子4,读取cookie文件
import http.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'))
 
 

5. 异常处理

一般可捕获3个异常类型,分别为URLError, HTTPError, ContentTooShortError
 
1. 打印异常原因, URLError:只有一个reason属性
from urllib import request, error
try:
response = request.urlopen('http://cuiqingcai.com/index.html')
except error.URLError as e:
print(e.reason)
 
2. HTTPError是URLError的子类,有三个属性:code,reason,headers
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')
 
 
3. 验证异常原因
import socket
import urllib.request
import urllib.error try:
response = urllib.request.urlopen('https://www.baidu.com',timeout=0.01)
except urllib.error.URLError as e:
print(type(e.reason))
if isinstance(e.reason, socket.timeout):
print('TIME OUT')
 
 

六. URL解析

 
urlparse模块
 
语法:urllib.parse.urlparse(urlstring, scheme='', allow_fragments=True)
 
1. 拆分URL并分段获取URL地址
from urllib.parse import urlparse

result = urlparse('http://www.baidu.com/index.html;user?id=5#comment')
print(type(result), result) 返回结果如下
<class 'urllib.parse.ParseResult'> ParseResult(scheme='http', netloc='www.baidu.com', path='/index.html', params='user', query='id=5', fragment='comment')
 
 
2. 1 URL中不写协议时,scheme参数指定协议类型
from urllib.parse import urlparse

result = urlparse('www.baidu.com/index.html;user?id=5#comment', scheme='https')
print(result)
返回结果如下
ParseResult(scheme='https', netloc='', path='www.baidu.com/index.html', params='user', query='id=5', fragment='comment')
 
 
2. 2 URL中有协议时,scheme参数指定协议类型无效
from urllib.parse import urlparse

result = urlparse('http://www.baidu.com/index.html;user?id=5#comment', scheme='https')
print(result)
返回结果
ParseResult(scheme='http', netloc='www.baidu.com', path='/index.html', params='user', query='id=5', fragment='comment')
 
 
3.1 allow_fragments:锚点链接
from urllib.parse import urlparse

result = urlparse('http://www.baidu.com/index.html;user?id=5#comment', allow_fragments=False)
print(result)
返回结果, 值为False时,锚点值拼接到query中
ParseResult(scheme='http', netloc='www.baidu.com', path='/index.html', params='user', query='id=5#comment', fragment='')
 
 
3.2 当query和params为空时,拼接到前面
from urllib.parse import urlparse

result = urlparse('http://www.baidu.com/index.html#comment', allow_fragments=False)
print(result)
返回结果
ParseResult(scheme='http', netloc='www.baidu.com', path='/index.html#comment', params='', query='', fragment='')
 
 
4. urlunparse模块,拼接url
from urllib.parse import urlunparse

data = ['http', 'www.baidu.com', 'index.html', 'user', 'a=6', 'comment']
print(urlunparse(data))
返回结果:
http://www.baidu.com/index.html;user?a=6#comment
 
 
5. urljoin模块
 
有相同字段的URL,后面的覆盖前面的
from urllib.parse import urljoin

print(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'))

返回结果为

 
 
 
6. urlencode模块:把字典对象转换为get请求参数
from urllib.parse import urlencode

params = {
'name': 'germey',
'age': 22
}
base_url = 'http://www.baidu.com?'
url = base_url + urlencode(params)
print(url)
返回
 
 
 
 
 

爬虫2:urllib的更多相关文章

  1. python 3.x 爬虫基础---Urllib详解

    python 3.x 爬虫基础 python 3.x 爬虫基础---http headers详解 python 3.x 爬虫基础---Urllib详解 前言 爬虫也了解了一段时间了希望在半个月的时间内 ...

  2. Python爬虫之urllib模块2

    Python爬虫之urllib模块2 本文来自网友投稿 作者:PG-55,一个待毕业待就业的二流大学生. 看了一下上一节的反馈,有些同学认为这个没什么意义,也有的同学觉得太简单,关于Beautiful ...

  3. Python爬虫之urllib模块1

    Python爬虫之urllib模块1 本文来自网友投稿.作者PG,一个待毕业待就业二流大学生.玄魂工作室未对该文章内容做任何改变. 因为本人一直对推理悬疑比较感兴趣,所以这次爬取的网站也是平时看一些悬 ...

  4. python爬虫之urllib库(三)

    python爬虫之urllib库(三) urllib库 访问网页都是通过HTTP协议进行的,而HTTP协议是一种无状态的协议,即记不住来者何人.举个栗子,天猫上买东西,需要先登录天猫账号进入主页,再去 ...

  5. python爬虫之urllib库(二)

    python爬虫之urllib库(二) urllib库 超时设置 网页长时间无法响应的,系统会判断网页超时,无法打开网页.对于爬虫而言,我们作为网页的访问者,不能一直等着服务器给我们返回错误信息,耗费 ...

  6. python爬虫之urllib库(一)

    python爬虫之urllib库(一) urllib库 urllib库是python提供的一种用于操作URL的模块,python2中是urllib和urllib2两个库文件,python3中整合在了u ...

  7. python爬虫之urllib库

    请求库 urllib urllib主要分为几个部分 urllib.request 发送请求urllib.error 处理请求过程中出现的异常urllib.parse 处理urlurllib.robot ...

  8. 练手爬虫用urllib模块获取

    练手爬虫用urllib模块获取 有个人看一段python2的代码有很多错误 import re import urllib def getHtml(url): page = urllib.urlope ...

  9. Python爬虫之urllib.parse详解

    Python爬虫之urllib.parse 转载地址 Python 中的 urllib.parse 模块提供了很多解析和组建 URL 的函数. 解析url 解析url( urlparse() ) ur ...

  10. 爬虫---request+++urllib

    网络爬虫(又被称为网页蜘蛛,网络机器人,在FOAF社区中间,更经常的称为网页追逐者),是一种按照一定的规则,自动地抓取万维网信息的程序或者脚本.另外一些不常使用的名字还有蚂蚁.自动索引.模拟程序或者蠕 ...

随机推荐

  1. SQLServer锁的机制

    SQLServer锁的机制:共享锁(S)排它锁(X)更新锁(U)意向共享 (IS)意向排它 (IX) 意向排它共享 (SIX)架构修改(Sch-M) 架构稳定性(Sch-S)大容量更新(BU)

  2. YourKit Java Profiler安装和破解

    YourKit Java Profiler是业界领先的Java性能剖析工具.其独立版本安装成功且首次启动 YourKit Java Profiler 后,会弹出一个对话框,让用户选择 YourKit ...

  3. 二分图 and code1170 双栈排序

    6.6二分图 二分图是这样一个图: 有两顶点集且图中每条边的的两个顶点分别位于两个顶点集中,每个顶点集中没有边直接相连接. 无向图G为二分图的充分必要条件是,G至少有两个顶点,且其所有回路的长度均为偶 ...

  4. 统计学中z分布、t分布、F分布及χ^2分布

    Z就是正态分布,X^2分布是一个正态分布的平方,t分布是一个正态分布除以(一个X^2分布除以它的自由度然后开根号),F分布是两个卡方分布分布除以他们各自的自由度再相除 比如X是一个Z分布,Y(n)=X ...

  5. VS中的Debug 和 Release 编译方式的本质区别

    VS中的Debug 和 Release 编译方式的本质区别 Debug 通常称为调试版本,它包含调试信息,并且不作任何优化,便于程序员调试程序.Release 称为发布版本,它往往是进行了各种优化,使 ...

  6. in操作符

    // Arrays,数组:下标 in array,length也可以 var trees = new Array("redwood", "bay", " ...

  7. 深海划水队项目----七天冲刺之day3

    上完选修后的站立式会议: 工作进度 昨天已完成的工作: 推进开发进度,进一步理清开发思路. 今天计划完成的工作: 生成游戏块的类,其中包括7种不同的游戏块,每个游戏块又可以通过旋转得到另外一种形态. ...

  8. svn: Can't convert string from 'UTF-8' to native encoding: 解决办法

    在linux中,svn co 或 svn up 时有中文文件名的文件的话,可能会报下面的错: [root@linkea-dev-srv1 ~]# svn upsvn: Can't convert st ...

  9. Linux 批量管理工具

    pssh/pscp(Python) ansible(Python) saltstack(Python) chef puppet(Ruby) fabric(Python)

  10. jenkins Build Flow job 输入参数获取和传递

    jenkins Build Flow job 输入参数获取和传递 如果设置Build Flow的job,怎样获取手工输入的参数. 1. 指定构建参数 job配置中,勾选"参数化构建" ...