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. STP-14-MST配置

    在配置MST之前,工程师要进行一定程度的预先规划.首先,必须决定是否应该使用多区域设计,以及如何设置边界.多区域的设计使得每个区域都有独立的MST实例编号.VLAN到实例的映射,以及独立的实例根.整体 ...

  2. python大战机器学习——聚类和EM算法

    注:本文中涉及到的公式一律省略(公式不好敲出来),若想了解公式的具体实现,请参考原著. 1.基本概念 (1)聚类的思想: 将数据集划分为若干个不想交的子集(称为一个簇cluster),每个簇潜在地对应 ...

  3. JavaScript 中Array数组的几个内置函数

    本文章内容均参考<JavaScript高级程序设计第三版> 今天在看JavaScript书籍的时候,看到之前没有了解过的JavaScript中Array的几个内置函数对象,为了之后再开发工 ...

  4. NET Core中使用Redis和Memcached

    .NET Core中使用Redis和Memcached的序列化问题   前言 在使用分布式缓存的时候,都不可避免的要做这样一步操作,将数据序列化后再存储到缓存中去. 序列化这一操作,或许是显式的,或许 ...

  5. .net core实现的全程序跟踪

    Ocelot中使用Butterfly实践 ocelot   Ocelot + Consul实践   Ocelot中使用Butterfly实践   Ocelot监控     Ocelot统一权限验证   ...

  6. C. An impassioned circulation of affection DP

    http://codeforces.com/contest/814/problem/C 12ooyomioomioo21 o2 o 这题我是用dp解的,不过好像很慢,比赛的时候算了下不会mle,就没滚 ...

  7. Centos7.2内网环境安装MySQL5.7.24

    1.配置本地yum源 内网环境,首先需要配置本地yum源,以解决MySQL的依赖安装,具体参考该文:点击打开 2.查看服务器环境 uname -a 3.去官网下载MySQL安装包 MySQL官网网址: ...

  8. ASPECTJ 注解。。。

    public interface ISomeService { public void doSome(); public String dade(); } public class SomeServi ...

  9. UIScrollView使用stoboard自动布局

    使用stoboard布局 scrollView 是有点麻烦的,首先我们往往约束好一个 scrollView 然后在添加子控件,此时都会报错,原因是, scrollView必须确定滚动范围 然后在使用V ...

  10. Springboot优点总结

    谈到 Spring Boot,就让我们先来了解它的优点 . 依据官方的文档, Spring Boot 的优点如下: --创建独立的 Spring 应用程序 : --嵌入的 Tomcat . Jetty ...