python中urllib包的网络请求教程


Posted in Python onApril 19, 2022

一、简介

  • 是一个 python 内置包,不需要额外安装即可使用
  • urllib 是 Python 标准库中用于网络请求的库,内置四个模块,分别是
  • urllib.request:用来打开和读取 url,可以用它来模拟发送请求,获取网页响应内容
  • urllib.error:用来处理 urllib.request 引起的异常,保证程序的正常执行
  • urllib.parse:用来解析 url,可以对 url 进行拆分、合并等
  • urllib.robotparse:用来解析 robots.txt 文件,判断网站是否能够进行爬取

二、发起请求

import urllib.request

# 方法一
resp = urllib.request.urlopen('http://www.baidu.com', timeout=1)
print(resp.read().decode('utf-8'))

# 方法二
request = urllib.request.Request('http://www.baidu.com')
response = urllib.request.urlopen(request)
print(response.read().decode('utf-8'))

三、携带参数请求

  • 请求某些网页时需要携带一些数据
import urllib.parse
import urllib.request

params = {
'name':'autofelix',
'age':'25'
}

data = bytes(urllib.parse.urlencode(params), encoding='utf8')
response = urllib.request.urlopen("http://www.baidu.com/", data=data)
print(response.read().decode('utf-8'))

四、获取响应数据

import urllib.request

resp = urllib.request.urlopen('http://www.baidu.com')
print(type(resp))
print(resp.status)
print(resp.geturl())
print(resp.getcode())
print(resp.info())
print(resp.getheaders())
print(resp.getheader('Server'))

五、设置headers

import urllib.request

headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'
}
request = urllib.request.Request(url="http://tieba.baidu.com/", headers=headers)
response = urllib.request.urlopen(request)
print(response.read().decode('utf-8'))

六、使用代理

import urllib.request

proxys = urllib.request.ProxyHandler({
'http': 'proxy.cn:8080',
'https': 'proxy.cn:8080'
})

opener = urllib.request.build_opener(proxys)
urllib.request.install_opener(opener)

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

七、认证登录

  • 有些网站需要携带账号和密码进行登录之后才能继续浏览网页
import urllib.request

url = "http://www.baidu.com/"
user = 'autofelix'
password = '123456'
pwdmgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
pwdmgr.add_password(None,url,user,password)

auth_handler = urllib.request.HTTPBasicAuthHandler(pwdmgr)
opener = urllib.request.build_opener(auth_handler)
response = opener.open(url)
print(response.read().decode('utf-8'))

八、设置cookie

  • 如果请求的页面每次需要身份验证,我们可以使用 Cookies 来自动登录,免去重复登录验证的操作
import http.cookiejar
import urllib.request

cookie = http.cookiejar.CookieJar()
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler)
response = opener.open("http://www.baidu.com/")

f = open('cookie.txt', 'a')
for item in cookie:
f.write(item.name+" = "+item.value+'\n')
f.close()

九、异常处理

from urllib import error, request

try:
resp = request.urlopen('http://www.baidu.com')
except error.URLError as e:
print(e.reason)

十、HTTP异常

from urllib import error, request

try:
resp = request.urlopen('http://www.baidu.com')
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')

十一、超时异常

import socket, urllib.request, urllib.error

try:
resp = urllib.request.urlopen('http://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')

十二、解析编码

from urllib import parse

name = parse.quote('飞兔小哥')

# 转换回来
parse.unquote(name)

十三、参数拼接

  • 在访问url时,我们常常需要传递很多的url参数
  • 而如果用字符串的方法去拼接url的话,会比较麻烦
from urllib import parse

params = {'name': '飞兔', 'age': '27', 'height': '178'}
parse.urlencode(params)

十四、请求链接解析

from urllib.parse import urlparse

result = urlparse('http://www.baidu.com/index.html?user=autofelix')
print(type(result))
print(result)

十五、拼接链接

  • 如果拼接的是两个链接,则以返回后面的链接
  • 如果拼接是一个链接和参数,则返回拼接后的内容
from urllib.parse import urljoin

print(urljoin('http://www.baidu.com', 'index.html'))

十六、字典转换参数

from urllib.parse import urlencode

params = {
'name': 'autofelix',
'age': 27
}
baseUrl = 'http://www.baidu.com?'
print(baseUrl + urlencode(params))

到此这篇关于python 包中的 urllib 网络请求教程的文章就介绍到这了!

Python 相关文章推荐
用python实现批量重命名文件的代码
May 25 Python
Mac下Supervisor进程监控管理工具的安装与配置
Dec 16 Python
python获得两个数组交集、并集、差集的方法
Mar 27 Python
python对url格式解析的方法
May 13 Python
Python中的左斜杠、右斜杠(正斜杠和反斜杠)
Aug 30 Python
Python循环语句中else的用法总结
Sep 11 Python
python3操作mysql数据库的方法
Jun 23 Python
Django中的Signal代码详解
Feb 05 Python
python 遗传算法求函数极值的实现代码
Feb 11 Python
Python实现动态给类和对象添加属性和方法操作示例
Feb 29 Python
Python爬虫制作翻译程序的示例代码
Feb 22 Python
Python中使用ipython的详细教程
Jun 22 Python
python APScheduler执行定时任务介绍
Apr 19 #Python
Python数据可视化之Seaborn的安装及使用
python 闭包函数详细介绍
Apr 19 #Python
Python  lambda匿名函数和三元运算符
Apr 19 #Python
Python使用mitmproxy工具监控手机 下载手机小视频
使用Python通过企业微信应用给企业成员发消息
Python用any()函数检查字符串中的字母以及如何使用all()函数
Apr 14 #Python
You might like
php Memcache 中实现消息队列
2009/11/24 PHP
php及codeigniter使用session-cookie的方法(详解)
2017/04/06 PHP
php正则表达式使用方法整理集合
2020/01/31 PHP
基于jquery的图片幻灯展示源码
2012/07/15 Javascript
ajax异步刷新实现更新数据库
2012/12/03 Javascript
js格式化金额可选是否带千分位以及保留精度
2014/01/28 Javascript
jQuery移动页面开发中的触摸事件与虚拟鼠标事件简介
2015/12/03 Javascript
Angular外部使用js调用Angular控制器中的函数方法或变量用法示例
2016/08/05 Javascript
js实现一个可以兼容PC端和移动端的div拖动效果实例
2016/12/09 Javascript
jQuery插件echarts去掉垂直网格线用法示例
2017/03/03 Javascript
详解IOS微信上Vue单页面应用JSSDK签名失败解决方案
2018/11/14 Javascript
vuedraggable+element ui实现页面控件拖拽排序效果
2020/07/29 Javascript
vue缓存的keepalive页面刷新数据的方法
2019/04/23 Javascript
js针对图片加载失败的处理方法分析
2019/08/24 Javascript
js脚本中执行java后台代码方法解析
2019/10/11 Javascript
React实现阿里云OSS上传文件的示例
2020/08/10 Javascript
[01:04:29]DOTA2-DPC中国联赛 正赛 Phoenix vs XG BO3 第二场 1月31日
2021/03/11 DOTA
Python使用dis模块把Python反编译为字节码的用法详解
2016/06/14 Python
遍历python字典几种方法总结(推荐)
2016/09/11 Python
Flask框架模板继承实现方法分析
2019/07/31 Python
Python3之乱码\xe6\x97\xa0\xe6\xb3\x95处理方式
2020/05/11 Python
详解Python设计模式之策略模式
2020/06/15 Python
Python3爬虫中pyspider的安装步骤
2020/07/29 Python
浅析HTML5:'data-'属性的作用
2018/01/23 HTML / CSS
Kent & Curwen:与大卫·贝克汉姆合作
2017/06/13 全球购物
Shopty西班牙:缝纫机在线销售
2018/01/26 全球购物
Bealls Florida百货商店:生活服饰、家居装饰和鞋子
2018/02/23 全球购物
Ancheer官方户外和运动商店:销售电动自行车
2019/08/07 全球购物
全运会口号
2014/06/20 职场文书
教师批评与自我批评发言稿
2014/10/15 职场文书
2014小学教师个人工作总结
2014/11/10 职场文书
漂亮妈妈观后感
2015/06/08 职场文书
幼儿园国培研修日志
2015/11/13 职场文书
python tqdm用法及实例详解
2021/06/16 Python
OpenCV 图像梯度的实现方法
2021/07/25 Python
宫崎骏十大动画电影,宫崎骏好看的动画电影排名
2022/03/22 日漫