Urllib库详解

Python内置的Http请求库:

* urllib.request 请求模块

* urllib.error 异常处理模块

* urllib.parse url解析模块

* urllib.robotparser robots.txt解析模块

相比在python2基础上的变化

Python2

import urllib2
response = urllib2.urlopen('http://www.baidu.com')

Python3

import urllib.request
response = urllib.request.urlopen('http://www.baidu.com')

urlopen实现get方法

import urllib.request
response = urllib.request.urlopen('http://www.baidu.com')
print(response.read().decode('utf-8'))

urlopen实现post方法

import urllib.parse
import urllib.request
data = bytes(urllib.parse.urlencode({'word':'hello'}),encoding='utf-8')
response = urllib.request.urlopen('http://httpbin.org/post',data=data)

urlopen实现超时设置

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

将时间缩短,查看效果

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))

<class 'http.client.HTTPResponse'>

状态码、响应头

import urllib.request
response = urllib.request.
response = urllib.request.urlopen('https://www.python.org')
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'), ('Content-Length', '50069'), ('Accept-Ranges', 'bytes'), ('Date', 'Mon, 26 Nov 2018 10:16:51 GMT'), ('Via', '1.1 varnish'), ('Age', '1872'), ('Connection', 'close'), ('X-Served-By', 'cache-iad2144-IAD, cache-tyo19943-TYO'), ('X-Cache', 'HIT, HIT'), ('X-Cache-Hits', '2, 4331'), ('X-Timer', 'S1543227412.955266,VS0,VE0'), ('Vary', 'Cookie'),

('Strict-Transport-Security', 'max-age=63072000; includeSubDomains')]

nginx

Request

from urllib import request,parse
url = 'http://httpbin.org/post'
headers = {
'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36',
'Host':'httpbin.org' }
dict = { 'name':'Germey' } data = bytes(parse.urlencode(dict),encoding='utf-8')
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/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36"

},

"json": null,

"origin": "58.34.235.37",

"url": "http://httpbin.org/post"

}

from urllib import request,parse
url = 'http://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'))

{

"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": "58.34.235.37",

"url": "http://httpbin.org/post"

}

Handler

代理

import urllib.request
proxy_handler = urllib.request.ProxyHandler({
'http':'http://127.0.0.1:9319',
'https':'https://127.0.0.1:9319'
})
opener = urllib.request.build_opener(proxy_handler)
response = opener.open('http://www.baidu.com')
print(response.read())

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)

BAIDUID=DF51E1D71641196283719D090EEA14DA:FG=1

BIDUPSID=DF51E1D71641196283719D090EEA14DA

H_PS_PSSID=1433_21086_27508

PSTM=1543232201

delPer=0

BDSVRTM=0

BD_HOME=0

保存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)

 Netscape HTTP Cookie File

 http://curl.haxx.se/rfc/cookie_spec.html

#&nbsp;This is a generated file!  Do not edit.

.baidu.com TRUE / FALSE 3690716228 BAIDUID 3131EAE6351C0F474BF6E477B848A52B:FG=1

.baidu.com TRUE / FALSE 3690716228 BIDUPSID 3131EAE6351C0F474BF6E477B848A52B

.baidu.com TRUE / FALSE H_PS_PSSID 27775_1454_21088_20719

.baidu.com TRUE / FALSE 3690716228 PSTM 1543232581

.baidu.com TRUE / FALSE delPer 0

www.baidu.com FALSE / FALSE BDSVRTM 0

www.baidu.com FALSE / FALSE BD_HOME 0

import http.cookiejar,urllib.request
filename = 'cookie2.txt'
cookie = http.cookiejar.LWPCookieJar(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)

LWP-Cookies-2.0

Set-Cookie3: BAIDUID="38C33C024449D6412F80B85996FAA2F8:FG=1"; path="/"; domain=".baidu.com"; path_spec; domain_dot; expires="2086-12-14 15:01:56Z"; version=0

Set-Cookie3: BIDUPSID=38C33C024449D6412F80B85996FAA2F8; path="/"; domain=".baidu.com"; path_spec; domain_dot; expires="2086-12-14 15:01:56Z"; version=0

Set-Cookie3: H_PS_PSSID=1462_21088_22157; path="/"; domain=".baidu.com"; path_spec; domain_dot; discard; version=0

Set-Cookie3: PSTM=1543232869; path="/"; domain=".baidu.com"; path_spec; domain_dot; expires="2086-12-14 15:01:56Z"; version=0

Set-Cookie3: delPer=0; path="/"; domain=".baidu.com"; path_spec; domain_dot; discard; version=0

Set-Cookie3: BDSVRTM=0; path="/"; domain="www.baidu.com"; path_spec; discard; version=0

Set-Cookie3: BD_HOME=0; path="/"; domain="www.baidu.com"; path_spec; discard; version=0

加载Cookie文件

import http.cookiejar,urllib.request
cookie = http.cookiejar.LWPCookieJar()
cookie.load('cookie2.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'))

异常处理

from urllib import request,error
try:
response = request.urlopen('http://cuiiqdkfsj.com/insdfi.htm')
except error.URLError as e:
print(e.reason)

[Errno -2] Name or service not known

from urllib import request,error
try:
response = request.urlopen('http://www.baidu.com/dsjfi.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')

[Errno -2] Name or service not known

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

<class 'socket.timeout'>

TIME OUT

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

指定协议

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

取消锚点链接,向前拼接

from urllib.parse import urlparse
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='')

urlunparse

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

urljoin

urlencode

from urllib.parse import urlencode

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

Python爬虫系列-Urllib库详解的更多相关文章

  1. Python爬虫系列-Requests库详解

    Requests基于urllib,比urllib更加方便,可以节约我们大量的工作,完全满足HTTP测试需求. 实例引入 import requests response = requests.get( ...

  2. Python爬虫之urllib.parse详解

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

  3. Python爬虫:requests 库详解,cookie操作与实战

    原文 第三方库 requests是基于urllib编写的.比urllib库强大,非常适合爬虫的编写. 安装: pip install requests 简单的爬百度首页的例子: response.te ...

  4. 爬虫入门之urllib库详解(二)

    爬虫入门之urllib库详解(二) 1 urllib模块 urllib模块是一个运用于URL的包 urllib.request用于访问和读取URLS urllib.error包括了所有urllib.r ...

  5. python爬虫之urllib库(三)

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

  6. python爬虫之urllib库(二)

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

  7. python爬虫之urllib库(一)

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

  8. python爬虫知识点总结(三)urllib库详解

    一.什么是Urllib? 官方学习文档:https://docs.python.org/3/library/urllib.html 廖雪峰的网站:https://www.liaoxuefeng.com ...

  9. 爬虫--Urllib库详解

    1.什么是Urllib? 2.相比Python2的变化 3.用法讲解 (1)urlopen urlllb.request.urlopen(url,data=None[timeout,],cahle=N ...

随机推荐

  1. ESQL 查询数据报 参数类型“Edm.Decimal”和“Edm.Double”不兼容

    ESQL 查询数据报 参数类型“Edm.Decimal”和“Edm.Double”不兼容 System.Data.Entity.Core.Objects.ObjectQuery<TEntity& ...

  2. [题解](双向bfs)hdu_3085_Nightmare Ⅱ

    发现直接搜索比较麻烦,但是要同时两个人一起走容易想到双向bfs,比较普通, 在判断是否碰到ghost时只要比较两点的曼哈顿距离大小和step*2(即ghost扩散的距离)即可,仔细思考也是可以想到的 ...

  3. Token认证登录以及权限控制

    IdentityServer4实现Token认证登录以及权限控制   相关知识点 不再对IdentityServer4做相关介绍,博客园上已经有人出了相关的系列文章,不了解的可以看一下: 蟋蟀大神的: ...

  4. wepy开发踩坑记录

    与vue的不同 methods对象只存放tap等事件触发时的方法 events对象只存放$emit及$broadcast方法触发的事件 自定义方法及属性放在与methods平级的位置 props是动态 ...

  5. winform代码生成器(三)

    代码下载 地址 http://pan.baidu.com/s/1nuZjyat 接上面的两篇. 用户有时对 从表的 排版不喜欢,可以因某些字太长,需要拉长一些,有些则需要隐藏. 有什么办法呢? 我的思 ...

  6. Quartz.NET基础入门

    Quartz.NET是一个开源的作业调度框架,非常适合在平时的工作中,定时轮询数据库同步,定时邮件通知,定时处理数据等. Quartz.NET允许开发人员根据时间间隔(或天)来调度作业.它实现了作业和 ...

  7. webpack.config.js====CSS相关:css和scss配置loader

    1. 安装: //loader加载器加载css和sass模块 cnpm install style-loader css-loader node-sass sass-loader --save-dev ...

  8. hard link && symbolic link

    hard link :硬连接,多了一个inode,指向原始的inode,通过这个硬连接删除文件,文件不会被真正删除,而是删除这个inode symolic link:符号连接相当于快捷方式

  9. dubbo工作原理(3)

    dubbo主要核心部件 Remoting:网络通信框架,实现了sync-over-async和request-response消息机制. RPC:一个远程过程调用的抽象,支持负载均衡.容灾和集群功能. ...

  10. ABAP扫雷游戏

    . INCLUDE <icon>. CONSTANTS: " >> board cell values blank_hidden ', blank_marked TY ...