urllib库

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








转载于:https://www.cnblogs.com/wisir/p/9969833.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/250240.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

layer的删除询问框的使用

删除是个很需要谨慎的操作 我们需要进行确认 对了删除一般使用ajax操作 因为如果同url请求 处理 再返回 会有空白页 1.js自带的样式 <button type"button" data-toggle"tooltip" title"删除" class"btn btn-danger pull-right btn-xs&qu…

文献笔记(八)

一、基本信息 标题&#xff1a;MySQL数据库在自动测试系统中的应用 时间&#xff1a;2017 出版源&#xff1a;宁夏职业技术学院 领域分类&#xff1a;无线互联科技 二、研究背景 问题定义&#xff1a;文章介绍了MySQL数据库的特点&#xff0c;结合自动测试系统运行中的实际&…

Java --- 常用API

常用API 方法重载: 方法名相同,方法接收的参数不同 static: 修饰的类,可以直接使用类名进行调用 方法名说明public static abs(int a)返回参数的绝对值public static double ceil(double a)返回大于或等于public static double floor(double a)返回小于或等于参数的最大doubl…

9. 弹出键盘挡住input

1.) react 中 <input className"inp3" placeholder"密码" type"password" onChange{this.changepassword.bind(this)} onFocus{this.FocusFN.bind(this)} value{this.state.paswword}/> FocusFN(){ setTimeout(()>{ let pannel docume…

Linux初学时的一些常用命令(4)

1. 磁盘 查看当前磁盘使用情况 df -h查看某个文件大小 du -sh 文件名 如果不输入文件名&#xff0c;默认是当前目录的所有文件之和&#xff0c;即当前目录大小 2. 系统内存 free参数详解&#xff1a;https://blog.csdn.net/loongshawn/article/details/51758116 3. CPU CPU 使用…

小程序 --- 项目小练手Ⅰ

1. 接口文档 2. 帮助文档 小程序开发文档 mdn 阿里巴巴字体 iconfont 3. 项目搭建 3.1 新建小程序项目 填入自己的appid: wxdbf2b5e8c2f521a3 3.2 文件结构 一级目录 目录名作用styles存放公共样式components存放组件lib存放第三方库utils自己的帮助库request自己的接口…

vue aixos请求json

this.axios.get(/static/json/jinxiangZhe.json).then(res>{console.log(res);}).catch( error > {console.log(error,error)}) 转载于:https://www.cnblogs.com/SunShineM/p/9087734.html

小程序 --- Tab组件的封装

1. Tabs组件的封装 1.1 组件的引入 使用自定义的组件很简单,只需在使用组件的页面的配置文件.json文件中配置. // pages/goods_list/index.json {"usingComponents":{"Tabs": "../../components/Tabs/Tabs"} }然后再.wxml文件中使用即可 <…

爬虫之拉勾网职位获取

重点在于演示urllib.request.Request()请求中各项参数的 书写格式 譬如&#xff1a; url data headers...Demo演示&#xff08;POST请求&#xff09;:import urllib.requestimport urllib.parseimport json, jsonpath, csvurl "https://www.lagou.com/jobs/positionAjax.…

小程序 --- 点击放大功能、获取位置信息、文字样式省略、页面跳转(navigateTo)

1. 点击放大功能的实现 需求: 点击轮播图中的图片会实现放大预览的功能。首先有轮播图的样式如下 <!-- pages/goods_detail/index.wxml --> <!-- 轮播图 --> <view class"detail_swiper"><swiperautoplaycircularindicator-dots><swip…

Axure实现多用户注册验证

*****多用户登录验证***** 一、&#xff08;常规想法&#xff09;方法&#xff1a;工作量较大&#xff0c;做起来繁琐 1、当用户名和密码相同时怎么区分两者&#xff0c;使用冒号和括号来区分&#xff1a; eg. (admin:123456)(123456:demo)(zhang:san);由此得出前面是括号后面是…

前端插件网址

http://www.swiper.com.cn/转载于:https://www.cnblogs.com/luchuangao/p/9088057.html

python --- opencv部分学习

1. OpenCV 1.1 opencv概念 OpenCV是一个基于BSD许可(开源)发行的跨平台计算机视觉库可以运行在Linux、Windows、Android和Mac OS操作系统上它轻量级而且高效 – 有一系列C函数和少量 C 类构成同时提供了 Python、Ruby、MATLAB等语言的接口实现了图像处理和计算机视觉方面的很…

hive与hbase集成

环境: hadoop2.7.7 hive3.1.0 hbase2.0.2 1.jar包拷贝(之所以用这种方式,是因为这种方式最为稳妥,最开始用的软连接的方式,总是却少jar包)到hive的lib目录下删除所有hbase相关的jar rm -rf hbase-*.jar 接着从hbase的lib目录下拷贝所有的hbase相关jar cp -a hbasehome/lib/hba…

Winform(C#)输入完毕后,按Enter键触发Button事件

如在输入“用户名”和“密码”之后&#xff0c;有些人习惯按“回车键”来代替页面上的“确定”按钮&#xff0c;那么这一功能在Winform(C#)里如何实现呢&#xff1f; 触发密码文本框的KeyDown事件&#xff0c;代码如下&#xff1a; [c-sharp] view plaincopy private void txtP…

Maximum Xor Secondary(单调栈好题)

Maximum Xor Secondary CodeForces - 280B Bike loves looking for the second maximum element in the sequence. The second maximum element in the sequence of distinct numbers x1, x2, ..., xk (k > 1) is such maximum element xj, that the following inequa…

python --- udp的使用

1. python的模块导入规则 参考 1.1 系统自带模块 系统自带的模块直接import导入 import time import unittest1.2 第三方下载模块 第三方下载模块也可以直接导入 import HTMLTestRunner import requests1.3 导入模块的部分函数或类 from time import sleep,strftime fro…

杂项-公司:唯品会

ylbtech-杂项-公司&#xff1a;唯品会唯品会公司成立于2008年08月&#xff0c;2012年3月23日登陆美国纽约证券交易所上市&#xff08;股票代码&#xff1a;VIPS&#xff09;。成为华南第一家在美国纽交所上市的电子商务企业。主营B2C商城唯品会名牌折扣网站是一家致力于打造中高…

python --- 使用socket创建tcp服务

1. 网络-tcp 参考 1.1 tcp简介 介绍 TCP协议,传输控制协议(英语: Transmission Control Protocol, 缩写为TCP)是一种面向连接的、可靠的、基于字节流的传输层通信协议,由IETF的RFC 793定义. TCP通信需要经过创建连接、数据传送、终止连接三个步骤. TCP通信模型中,在通信开…

Linux基本的操作

一、为什么我们要学习Linux 相信大部分人的PC端都是用Windows系统的&#xff0c;那我们为什么要学习Linux这个操作系统呢&#xff1f;&#xff1f;&#xff1f;Windows图形化界面做得这么好&#xff0c;日常基本使用的话&#xff0c;学习成本几乎为零。 而Linux不一样&#xff…