python 包实现 urllib 网络请求操作
作者:autofelix 时间:2023-11-03 07:19:50
一、简介
是一个 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))
来源:https://blog.51cto.com/autofelix/5208214
标签:python,urllib,网络,请求
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python面向对象编程基础解析(一)
2021-08-10 15:05:12
PHP实现绘制二叉树图形显示功能详解【包括二叉搜索树、平衡树及红黑树】
2023-07-23 02:36:20
![](https://img.aspxhome.com/file/2023/9/553891_0s.png)
pycharm远程连接vagrant虚拟机中mariadb数据库
2024-01-13 19:11:33
![](https://img.aspxhome.com/file/2023/2/134692_0s.png)
详解Go语言中单链表的使用
2024-02-01 11:55:03
![](https://img.aspxhome.com/file/2023/1/109741_0s.jpg)
Python绘制1000响大地红鞭炮动态效果
2021-08-21 20:44:26
![](https://img.aspxhome.com/file/2023/9/66009_0s.gif)
asp如何判断一个电子信箱格式是否有效?
2010-01-12 20:18:00
mysql 5.7.13 安装配置方法图文教程(win10 64位)
2024-01-28 09:07:21
详解Pytorch如何利用yaml定义卷积网络
2023-02-16 10:46:01
关于MySQL的sql_mode合理设置详解
2024-01-22 20:44:14
![](https://img.aspxhome.com/file/2023/4/76154_0s.jpg)
网站图片与文本谁更重要?(中英文对照)
2008-10-17 10:25:00
Python中的异常处理相关语句基础学习笔记
2021-10-18 00:54:50
实现UTF8转换GB2312国标码的asp代码
2011-02-28 10:53:00
压缩包密码破解示例分享(类似典破解)
2022-10-17 17:03:37
php输出文字乱码的解决方法
2023-11-11 07:40:08
原生JS与jQuery编写简单选项卡
2024-04-30 09:52:52
解析mysql与Oracle update的区别
2024-01-25 01:35:55
Python3中多线程编程的队列运作示例
2022-06-15 23:27:49
python数据拟合之scipy.optimize.curve_fit解读
2021-05-27 01:48:49
![](https://img.aspxhome.com/file/2023/0/79550_0s.png)
Python Django框架设计模式详解
2021-01-16 12:52:40
![](https://img.aspxhome.com/file/2023/4/72864_0s.jpg)
sql2000挂起无法安装的问题的解决方法
2024-01-20 19:09:34