python内置的最基本的HTTP请求库,有以下四个模块:

urllib.request  请求模块

urllib.error    异常处理模块

urllib.parse   url解析模块

urllib.robotparser  robots.txt解析模块

urllib.request请求模块:

urllib.request.urlopen(url,data=None,[timeout,]*,cafile=None,capath=None,cadefault=False,context=None)

'''urlopen()函数'''
import urllib.request

response = urllib.request.urlopen("http://www.baidu.com")
print(response.read().decode("utf-8"))    #response.read()是bytes类型的数据,要转码。

import urllib.parse
data = bytes(urllib.parse.urlencode({'word':'hello'}),encoding='utf-8')
#该提交方式是post,data参数是bytes类型的键值对对象
response = urllib.request.urlopen("http://httpbin.org/post",data=data) #专门提供做http测试的网站
print(response.read())
#timeout是超时响应参数

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

import socket
import urllib.error
try:
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')
#响应类型
print(type(response)) #响应头、状态码
response = urllib.request.urlopen("https://www.python.org")
print(response.status) #得到响应的状态码
print(response.getheaders()) #得到响应的Response Headers
print(response.getheader("Server")) #根据键得到Response Headers中指定键的值
'''Request()函数:当urlopen()要传递headers等信息时候,就要用到Request()函数,
返回一个request对象作为urlopen()函数的一个参数。'''
import urllib.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(urllib.parse.urlencode(dict),encoding='utf-8')
req = urllib.request.Request(url=url,data=data,headers=headers,method='POST')
req.add_header('User-Agent','Mozilla/4.0(compatible;MSIE 5.5;Windows NT)') #可以单独添加header
response = urllib.request.urlopen(req)
print(response.read().decode('utf-8'))
'''cookie'''
import http.cookiejar,urllib.request
cookie = http.cookiejar.MozillaCookieJar()
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
filename = "cookieLWP.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)
#读取cookie
cookie = http.cookiejar.LWPCookieJar() #怎么存就怎么取
cookie.load('cookieLWP.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')) urllib.error异常处理模块:
'''异常处理'''
from urllib import error
try:
response = urllib.request.urlopen("https://www.cnblogs.com/wisir/index.html")
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") try:
response = urllib.request.urlopen("https://www.baidu.com",timeout=0.01)
except urllib.error.URLError as e:
print(e.reason)
if isinstance(e.reason,socket.timeout):
print('TIME OUT')


urllib.parse URL解析模块:
'''urlparse'''
# urllib.parse.urlparse(urlstring,scheme="",allow_fragments=True)
from urllib.parse import urlparse
result = urlparse("http://www.baidu.com/index.html;user?id=5#comment")
print(type(result),result) '''urlunparse:作用与urlparse相反,是将ParseResult类型的六个参数,合成一个完整的url。'''
from urllib.parse import urlunparse
data = ['http','www.baidu.com','index.html','user','a=6','comment']
print(urlunparse(data)) '''urljoin:以第二个参数为基准,若第二个参数没有ParseResult类型六个参数中的某一个,则用第一个参数作为补充。'''
from urllib.parse import urljoin
print(urljoin("http://www.baidu.com","FAQ.html"))
print(urljoin("http://www.baidu.com","https://www.cnblogs.com/wisir/")) '''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)

python3 urllib库官方文档:https://docs.python.org/3/library/urllib.html

urllib库的更多相关文章

  1. python--爬虫入门(七)urllib库初体验以及中文编码问题的探讨

    python系列均基于python3.4环境 ---------@_@? --------------------------------------------------------------- ...

  2. urllib库初体验以及中文编码问题的探讨

    提出问题:如何简单抓取一个网页的源码 解决方法:利用urllib库,抓取一个网页的源代码 ------------------------------------------------------- ...

  3. Python爬虫入门 Urllib库的基本使用

    1.分分钟扒一个网页下来 怎样扒网页呢?其实就是根据URL来获取它的网页信息,虽然我们在浏览器中看到的是一幅幅优美的画面,但是其实是由浏览器解释才呈现出来的,实质它是一段HTML代码,加 JS.CSS ...

  4. Python爬虫入门:Urllib库的基本使用

    1.分分钟扒一个网页下来 怎样扒网页呢?其实就是根据URL来获取它的网页信息,虽然我们在浏览器中看到的是一幅幅优美的画面,但是其实是由浏览器解释才呈现出来的,实质它 是一段HTML代码,加 JS.CS ...

  5. Python2/3中的urllib库

    urllib库对照速查表 Python2.X Python3.X urllib urllib.request, urllib.error, urllib.parse urllib2 urllib.re ...

  6. 芝麻HTTP:Python爬虫入门之Urllib库的基本使用

    1.分分钟扒一个网页下来 怎样扒网页呢?其实就是根据URL来获取它的网页信息,虽然我们在浏览器中看到的是一幅幅优美的画面,但是其实是由浏览器解释才呈现出来的,实质它是一段HTML代码,加 JS.CSS ...

  7. python爬虫 - Urllib库及cookie的使用

    http://blog.csdn.net/pipisorry/article/details/47905781 lz提示一点,python3中urllib包括了py2中的urllib+urllib2. ...

  8. Urllib库的使用

    一.任务描述   本实验任务主要对urllib库进行一些基本操作,通过完成本实验任务,要求学生熟练掌握urllib库的使用,并对urllib库的基本操作进行整理并填写工作任务报告. 二.任务目标 1. ...

  9. 对于python爬虫urllib库的一些理解(抽空更新)

    urllib库是Python中一个最基本的网络请求库.可以模拟浏览器的行为,向指定的服务器发送一个请求,并可以保存服务器返回的数据. urlopen函数: 在Python3的urllib库中,所有和网 ...

  10. (爬虫)urllib库

    一.爬虫简介 什么是爬虫?通俗来讲爬虫就是爬取网页数据的程序. 要了解爬虫,还需要了解HTTP协议和HTTPS协议:HTTP协议是超文本传输协议,是一种发布和接收HTML页面的传输协议:HTTPS协议 ...

随机推荐

  1. 数据库之mysql篇(6)—— mysql常用函数函数/自定义函数

    常用函数 运算函数 我相信你都能看懂,所以以上的不再做过多解释 然后还有个,前面漏掉的between and: 意指10是否在0到20之间,如果是返回1,否则返回0 日期函数 这个要稍微注意一下参数, ...

  2. Q2Day81

    性能相关 在编写爬虫时,性能的消耗主要在IO请求中,当单进程单线程模式下请求URL时必然会引起等待,从而使得请求整体变慢. import requests def fetch_async(url): ...

  3. django重定向

    return HttpResponseRedirect('/index/')# 重定向返回url格式:http://127.0.0.1:8000/index/会去掉前期的所有路由重新写入/index/ ...

  4. Windows Server 2016-WinSer 2016标准版与数据中心版的区别

    今天在整理文章的时候看到有读者问到他现在的测试环境是用的Windows Server 2016标准版,和我现阶段系列文章的环境是否有区别. 其实针对Windows Server 2016 Active ...

  5. python--私有属性--私有方法

    Class 定义类 def 初始化方法(形参) 属性1 属性2   私有属性(属性之前加--) def  方法1() print() 属性和方法定义好以后,在创建对象 对象=类名(“”) print( ...

  6. LeetCode算法题-Symmetric Tree(Java实现)

    这是悦乐书的第163次更新,第165篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第22题(顺位题号是101).给定二叉树,检查它是否是自身的镜像(即,围绕其中心对称). ...

  7. March 10th, 2018 Week 10th Saturday

    All good things must come to an end. 好景无常. Love is when the other person's happiness is more importa ...

  8. MY Views on Doctor-patient relationship 英语医患关系议论文

    MY Views on Doctor-patient relationship Author:Pleiades_Antares(www.cnblogs.com/irischen) 1. In rece ...

  9. 在win10 64位系统安装 lxml (Python 3.5)

    本想直接用pip install lxml 命令安装完事,但是由于安装过程中跟VS的一些东西冲突怎么都安装不上,搜索到以下方法,问题解决. 步骤: 1.下载跟python匹配的.whl 文件(lxml ...

  10. 百度统计api获取数据

    需求场景 想要了解每天多少人访问了网站,多少个新增用户,地域分布,点击了哪些页面,停留了多久,等等... 国内用的最多的就是百度统计吧,傻瓜式的注册然后插一段代码到项目里就行了. 最近也在自己的博客里 ...