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之引用和类属性的初步理解
May 15 Python
Python实现处理管道的方法
Jun 04 Python
通过Python来使用七牛云存储的方法详解
Aug 07 Python
python开发之基于thread线程搜索本地文件的方法
Nov 11 Python
使用py2exe在Windows下将Python程序转为exe文件
Mar 04 Python
Python常见加密模块用法分析【MD5,sha,crypt模块】
May 24 Python
Python语言描述KNN算法与Kd树
Dec 13 Python
详解分布式任务队列Celery使用说明
Nov 29 Python
对web.py设置favicon.ico的方法详解
Dec 04 Python
python之Flask实现简单登录功能的示例代码
Dec 24 Python
Python实现ATM系统
Feb 17 Python
python新手学习可变和不可变对象
Jun 11 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
2019十大人气国漫
2020/03/13 国漫
PHP Directory 函数的详解
2013/03/07 PHP
Ubuntu中启用php的mail()函数并解决发送邮件速度慢问题
2015/03/27 PHP
php三种实现多线程类似的方法
2015/10/30 PHP
PHP查询并删除数据库多列重复数据的方法(利用数组函数实现)
2016/02/23 PHP
Yii模型操作之criteria查找数据库的方法
2016/07/15 PHP
PHP实现redis限制单ip、单用户的访问次数功能示例
2018/06/16 PHP
Thinkphp5框架实现图片、音频和视频文件的上传功能详解
2019/08/27 PHP
yii 框架实现按天,月,年,自定义时间段统计数据的方法分析
2020/04/04 PHP
PHP+Mysql分布式事务与解决方案深入理解
2021/02/27 PHP
xtree.js 代码
2007/03/13 Javascript
JS 实现完美include载入实现代码
2010/08/05 Javascript
让input框实现类似百度的搜索提示(基于jquery事件监听)
2014/01/31 Javascript
浅析jquery数组删除指定元素的方法:grep()
2016/05/19 Javascript
jQuery解析返回的xml和json方法详解
2017/01/05 Javascript
Node.js读取文件内容示例
2017/03/07 Javascript
关于Vue项目跨平台运行问题的解决方法
2018/09/18 Javascript
JavaScript创建对象的四种常用模式实例分析
2019/01/11 Javascript
使用webpack搭建vue项目实现脚手架功能
2019/03/15 Javascript
前端js中的事件循环eventloop机制详解
2019/05/15 Javascript
微信小程序swiper禁止用户手动滑动代码实例
2019/08/23 Javascript
JavaScript async/await原理及实例解析
2020/12/02 Javascript
如何正确解决VuePress本地访问出现资源报错404的问题
2020/12/03 Vue.js
[15:46]教你分分钟做大人——沙王
2015/03/11 DOTA
Python函数的返回值、匿名函数lambda、filter函数、map函数、reduce函数用法实例分析
2019/12/26 Python
Python grequests模块使用场景及代码实例
2020/08/10 Python
CSS3实现背景透明文字不透明的示例代码
2018/06/25 HTML / CSS
Currentbody法国:健康与美容高科技产品
2020/08/16 全球购物
MediaMarkt比利时:欧洲最大电器连锁店
2020/12/21 全球购物
Hotels.com韩国:海外国内旅行所需的酒店和住宿预订网站
2020/05/08 全球购物
工作过失检讨书
2014/02/23 职场文书
革命英雄事迹演讲稿
2014/09/13 职场文书
就业协议书盖章的注意事项
2014/09/28 职场文书
群众路线批评与自我批评发言稿
2014/10/16 职场文书
2015年公司后勤管理工作总结
2015/05/13 职场文书
2016党员党课心得体会
2016/01/07 职场文书