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使用函数默认值实现函数静态变量的方法
Aug 18 Python
Python实现在线程里运行scrapy的方法
Apr 07 Python
谈谈Python进行验证码识别的一些想法
Jan 25 Python
Python实现二叉树结构与进行二叉树遍历的方法详解
May 24 Python
Python如何发布程序的详细教程
Oct 09 Python
浅谈pycharm下找不到sqlalchemy的问题
Dec 03 Python
python 接口实现 供第三方调用的例子
Aug 13 Python
pytorch点乘与叉乘示例讲解
Dec 27 Python
Python利用PyPDF2库获取PDF文件总页码实例
Apr 03 Python
PyTorch中torch.tensor与torch.Tensor的区别详解
May 18 Python
Python 利用Entrez库筛选下载PubMed文献摘要的示例
Nov 24 Python
10个顶级Python实用库推荐
Mar 04 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+jQuery+Ajax简单实现页面异步刷新
2016/08/08 PHP
Javascript操纵Cookie实现购物车程序
2006/11/23 Javascript
Extjs4 GridPanel 的几种样式使用介绍
2013/04/18 Javascript
灵活的理解JavaScript中的this指向
2016/02/25 Javascript
JS实现简单的星期格式转换功能示例
2018/07/23 Javascript
Vux+Axios拦截器增加loading的问题及实现方法
2018/11/08 Javascript
JS实现checkbox互斥(单选)功能示例
2019/05/04 Javascript
vue elementUI 表单校验功能之数组多层嵌套
2019/06/04 Javascript
Vue 使用beforeEach实现登录状态检查功能
2019/10/31 Javascript
微信小程序点击顶部导航栏切换样式代码实例
2019/11/12 Javascript
使用python解析xml成对应的html示例分享
2014/04/02 Python
利用Python中的输入和输出功能进行读取和写入的教程
2015/04/14 Python
Centos Python2 升级到Python3的简单实现
2016/06/21 Python
python实现给微信公众号发送消息的方法
2017/06/30 Python
解决Matplotlib图表不能在Pycharm中显示的问题
2018/05/24 Python
pygame实现俄罗斯方块游戏
2018/06/26 Python
详解Python安装scrapy的正确姿势
2018/06/26 Python
深入浅析Python中list的复制及深拷贝与浅拷贝
2018/09/03 Python
python实现飞机大战微信小游戏
2020/03/21 Python
python GUI库图形界面开发之PyQt5信号与槽机制、自定义信号基础介绍
2020/02/25 Python
canvas版人体时钟的实现示例
2021/01/29 HTML / CSS
兰蔻美国官网:Lancome美国
2017/04/25 全球购物
英国女士家居服网站:hush
2017/08/09 全球购物
美国滑雪和滑雪板商店:Buckman
2018/03/03 全球购物
Alexandre Birman美国官网:亚历山大·伯曼
2019/10/30 全球购物
10条PHP编程习惯
2014/05/26 面试题
信息管理专业推荐信
2013/10/29 职场文书
医院保洁服务方案
2014/06/11 职场文书
学生安全责任书范本
2014/07/24 职场文书
党员反对四风思想汇报范文
2014/10/25 职场文书
2015新生加入学生会自荐书
2015/03/24 职场文书
全民创业工作总结
2015/08/13 职场文书
Mybatis是这样防止sql注入的
2021/12/06 Java/Android
Java中try catch处理异常示例
2021/12/06 Java/Android
一次SQL查询优化原理分析(900W+数据从17s到300ms)
2022/06/10 SQL Server
python数字图像处理之图像自动阈值分割示例
2022/06/28 Python