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写的一个文本编辑器
Jan 23 Python
编写Python爬虫抓取豆瓣电影TOP100及用户头像的方法
Jan 20 Python
Python的requests网络编程包使用教程
Jul 11 Python
Python实现两款计算器功能示例
Dec 19 Python
Python3.5装饰器典型案例分析
Apr 30 Python
python自动发邮件总结及实例说明【推荐】
May 31 Python
Python实现的对一个数进行因式分解操作示例
Jun 27 Python
python闭包、深浅拷贝、垃圾回收、with语句知识点汇总
Mar 11 Python
Django中F函数的使用示例代码详解
Jul 06 Python
django form和field具体方法和属性说明
Jul 09 Python
python 如何区分return和yield
Sep 22 Python
Pandas的数据过滤实现
Jan 15 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防止sql注入示例分析和几种常见攻击正则表达式
2014/01/12 PHP
调试PHP程序的多种方法介绍
2014/11/06 PHP
PHP基于文件存储实现缓存的方法
2015/07/20 PHP
详解thinkphp实现excel数据的导入导出(附完整案例)
2016/12/29 PHP
php 判断页面或图片是否经过gzip压缩的方法
2017/04/05 PHP
laravel数据库查询结果自动转数组修改实例
2021/02/27 PHP
JQuery UI皮肤定制
2009/07/27 Javascript
js 实现菜单上下显示附效果图
2013/11/21 Javascript
JS实现匀速运动的代码实例
2013/11/29 Javascript
JavaScript插件化开发教程 (三)
2015/01/27 Javascript
JS+CSS实现六级网站导航主菜单效果
2015/09/28 Javascript
Nodejs 发送Post请求功能(发短信验证码例子)
2017/02/09 NodeJs
Angular.JS中select下拉框设置value的方法
2017/06/20 Javascript
JavaScript注册时密码强度校验代码
2017/06/30 Javascript
node.js+captchapng+jsonwebtoken实现登录验证示例
2017/08/17 Javascript
js实现Tab选项卡切换效果
2020/07/17 Javascript
AngularJS实现与后台服务器进行交互的示例讲解
2018/08/13 Javascript
JavaScript实现多个物体同时运动
2020/03/12 Javascript
[27:53]2014 DOTA2华西杯精英邀请赛 5 24 NewBee VS iG
2014/05/26 DOTA
[04:32]玩具屠夫中文语音节选
2020/08/23 DOTA
深入理解Python中变量赋值的问题
2017/01/12 Python
python实现的正则表达式功能入门教程【经典】
2017/06/05 Python
python实现AES加密和解密
2019/03/27 Python
python使用openCV遍历文件夹里所有视频文件并保存成图片
2020/01/14 Python
python实现3D地图可视化
2020/03/25 Python
html5小程序飞入购物车(抛物线绘制运动轨迹点)
2020/10/19 HTML / CSS
英国豪华文具和皮具配件经典老品牌:Smythson(斯迈森)
2018/04/19 全球购物
工作自荐信
2013/12/11 职场文书
商铺租赁意向书
2014/04/01 职场文书
小学生迎国庆演讲稿
2014/09/05 职场文书
法人委托书范本
2014/09/15 职场文书
2014小学数学教研组工作总结
2014/12/06 职场文书
个人汇报材料范文
2014/12/30 职场文书
初婚初育证明范本
2015/06/18 职场文书
创业计划书之酒厂
2019/10/14 职场文书
python内置模块之上下文管理contextlib
2022/06/14 Python