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中使用SimpleParse模块进行解析的教程
Apr 11 Python
Python实现定时执行任务的三种方式简单示例
Mar 30 Python
Python搭建Spark分布式集群环境
Jul 05 Python
python变量的存储原理详解
Jul 10 Python
wxpython实现按钮切换界面的方法
Nov 19 Python
把vgg-face.mat权重迁移到pytorch模型示例
Dec 27 Python
Django多数据库配置及逆向生成model教程
Mar 28 Python
配置python的编程环境之Anaconda + VSCode的教程
Mar 29 Python
PyQt5 控件字体样式等设置的实现
May 13 Python
详解python中的lambda与sorted函数
Sep 04 Python
pycharm2020.1.2永久破解激活教程,实测有效
Oct 29 Python
python 基于Apscheduler实现定时任务
Dec 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实现自动对图片进行滚动显示的方法
2015/03/12 PHP
PHP模拟QQ登录的方法
2015/07/29 PHP
PHP PDOStatement::debugDumpParams讲解
2019/01/30 PHP
js实现宇宙星空背景效果的方法
2015/03/03 Javascript
浅谈javascript属性onresize
2015/04/20 Javascript
js模仿php中strtotime()与date()函数实现方法
2015/08/11 Javascript
程序员必知35个jQuery 代码片段
2015/11/05 Javascript
jquery中取消和绑定hover事件的实现代码
2016/06/02 Javascript
ionic组件ion-tabs选项卡切换效果实例
2016/08/27 Javascript
jQuery事件用法详解
2016/10/06 Javascript
浅谈jQuery绑定事件会叠加的解决方法和心得总结
2016/10/26 Javascript
Vue2.0 UI框架ElementUI使用方法详解
2017/04/14 Javascript
vue实现引入本地json的方法分析
2018/07/12 Javascript
vue mounted 调用两次的完美解决办法
2018/10/29 Javascript
React组件对子组件children进行加强的方法
2019/06/23 Javascript
微信小程序(订阅消息)功能
2019/10/25 Javascript
vue form表单post请求结合Servlet实现文件上传功能
2021/01/22 Vue.js
js实现验证码干扰(动态)
2021/02/23 Javascript
[26:52]LGD vs EG 2018国际邀请赛小组赛BO2 第一场 8.17
2018/08/18 DOTA
django反向解析URL和URL命名空间的方法
2018/06/05 Python
python 通过 socket 发送文件的实例代码
2018/08/14 Python
对python xlrd读取datetime类型数据的方法详解
2018/12/26 Python
pytorch GAN生成对抗网络实例
2020/01/10 Python
Python autoescape标签用法解析
2020/01/17 Python
浅谈python3 构造函数和析构函数
2020/03/12 Python
mac系统下安装pycharm、永久激活、中文汉化详细教程
2020/11/24 Python
HTML5 Canvas——用路径描画线条实例介绍
2013/06/09 HTML / CSS
特步官方商城:Xtep
2017/03/21 全球购物
什么是servlet
2012/05/08 面试题
医药代表个人求职信范本
2013/12/19 职场文书
决心书范文
2014/03/11 职场文书
个人总结格式范文
2015/03/09 职场文书
2019各种保证书范文
2019/06/24 职场文书
HTML5中 rem适配方案与 viewport 适配问题详解
2021/04/27 HTML / CSS
以MySQL5.7为例了解一下执行计划
2022/04/13 MySQL
Python Matplotlib绘制等高线图与渐变色扇形图
2022/04/14 Python