千家信息网

python包中的urllib网络请求怎么实现

发表于:2025-11-08 作者:千家信息网编辑
千家信息网最后更新 2025年11月08日,这篇文章主要讲解了"python包中的urllib网络请求怎么实现",文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习"python包中的urllib网络请求
千家信息网最后更新 2025年11月08日python包中的urllib网络请求怎么实现

这篇文章主要讲解了"python包中的urllib网络请求怎么实现",文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习"python包中的urllib网络请求怎么实现"吧!

一、简介

  • 是一个 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.parseimport urllib.requestparams = {'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.requestresp = 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.requestheaders = {'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.requestproxys = 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.requesturl = "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.cookiejarimport urllib.requestcookie = 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, requesttry:resp = request.urlopen('http://www.baidu.com')except error.URLError as e:print(e.reason)

十、HTTP异常

from urllib import error, requesttry: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.errortry: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 parsename = parse.quote('飞兔小哥')# 转换回来parse.unquote(name)

十三、参数拼接

  • 在访问url时,我们常常需要传递很多的url参数

  • 而如果用字符串的方法去拼接url的话,会比较麻烦

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

十四、请求链接解析

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

十五、拼接链接

  • 如果拼接的是两个链接,则以返回后面的链接

  • 如果拼接是一个链接和参数,则返回拼接后的内容

from urllib.parse import urljoinprint(urljoin('http://www.baidu.com', 'index.html'))

十六、字典转换参数

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

感谢各位的阅读,以上就是"python包中的urllib网络请求怎么实现"的内容了,经过本文的学习后,相信大家对python包中的urllib网络请求怎么实现这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是,小编将为大家推送更多相关知识点的文章,欢迎关注!

网络 参数 链接 内容 登录 方法 网页 学习 验证 数据 网站 处理 两个 字典 字符 字符串 密码 就是 思路 情况 数据库的安全要保护哪些东西 数据库安全各自的含义是什么 生产安全数据库录入 数据库的安全性及管理 数据库安全策略包含哪些 海淀数据库安全审计系统 建立农村房屋安全信息数据库 易用的数据库客户端支持安全管理 连接数据库失败ssl安全错误 数据库的锁怎样保障安全 网络安全事件处置情况报告 天津税控盘安全接入服务器地址 软件开发工程师是不是很累 金融行业网络安全风险大吗 军营网络安全宣传周黑板报 深圳市富链软件开发 传统网络安全企业 数学对网络技术的作用 黄石软件开发报价 计算机网络技术英语要求高吗 单招网络技术实操 数据库与基础知识 奉贤区智能化软件开发规格尺寸 江苏品质刀片服务器设计 学网络安全需要什么技术 数据库值太大 反诈骗网络安全作文450字 银川一互联网科技公司被罚 山东高校网络安全研究生 灵山县电信域名服务器怎么填 美丽修行软件开发 财务软件开发公司排名 服务器过载怎么回事 计算机网络技术的就业方向与前景 网络安全技术实训代理防火墙 关系数据库中表是什么 数据库插入语句的返回值类型 苏州通用软件开发代理商 捷配互联网科技有限公司 密码网络安全检测
0