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 相关文章推荐
利用Python2下载单张图片与爬取网页图片实例代码
Dec 25 Python
Python实现pdf文档转txt的方法示例
Jan 19 Python
Python之dict(或对象)与json之间的互相转化实例
Jun 05 Python
matplotlib实现区域颜色填充
Mar 18 Python
PyQt5实现简易电子词典
Jun 25 Python
利用Python复制文件的9种方法总结
Sep 02 Python
python3实现用turtle模块画一棵随机樱花树
Nov 21 Python
Django crontab定时任务模块操作方法解析
Sep 10 Python
call在Python中改进数列的实例讲解
Dec 09 Python
Python入门基础之数字字符串与列表
Feb 01 Python
python如何获取网络数据
Apr 11 Python
Python实现老照片修复之上色小技巧
Oct 16 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获取网页内容方法总结
2008/12/04 PHP
php array_flip() 删除数组重复元素
2009/01/14 PHP
CodeIgniter模板引擎使用实例
2014/07/15 PHP
PHP中调用C/C++制作的动态链接库的教程
2016/03/10 PHP
php使用ffmpeg向视频中添加文字字幕的实现方法
2016/05/23 PHP
一些常用弹出窗口/拖放/异步文件上传等实用代码
2013/01/06 Javascript
js关闭当前页面(窗口)的几种方式总结
2013/03/05 Javascript
jQuery 事件的命名空间简单了解
2013/11/22 Javascript
JavaScript编写连连看小游戏
2015/07/07 Javascript
详解JavaScript的回调函数
2015/11/20 Javascript
浅谈JavaScript 函数参数传递到底是值传递还是引用传递
2016/08/23 Javascript
javascript判断firebug是否开启的方法
2016/11/23 Javascript
react-redux中connect()方法详细解析
2017/05/27 Javascript
灵活使用console让js调试更简单的方法步骤
2019/04/23 Javascript
由Python运算π的值深入Python中科学计算的实现
2015/04/17 Python
django之常用命令详解
2016/06/30 Python
Python 用Redis简单实现分布式爬虫的方法
2017/11/23 Python
K-近邻算法的python实现代码分享
2017/12/09 Python
python3学习之Splash的安装与实例教程
2018/07/09 Python
python模块导入的细节详解
2018/12/10 Python
python DataFrame 取差集实例
2019/01/30 Python
python3编写ThinkPHP命令执行Getshell的方法
2019/02/26 Python
2019 Python最新面试题及答案16道题
2019/04/11 Python
详解Ubuntu环境下部署Django+uwsgi+nginx总结
2020/04/02 Python
scrapy框架携带cookie访问淘宝购物车功能的实现代码
2020/07/07 Python
python实现图像高斯金字塔的示例代码
2020/12/11 Python
HTML5 Canvas锯齿图代码实例
2014/04/10 HTML / CSS
OPPO手机官方商城:中国手机市场出货量第一品牌
2017/10/18 全球购物
红色连衣裙精品店:Red Dress Boutique
2018/08/11 全球购物
一年级语文教学反思
2014/02/13 职场文书
婚纱摄影师求职信
2014/03/07 职场文书
未受刑事制裁公证证明
2014/09/20 职场文书
党员“一帮一”活动总结
2015/05/07 职场文书
消防安全主题班会
2015/08/12 职场文书
党员心得体会范文2016
2016/01/23 职场文书
导游词之上饶龟峰
2019/10/25 职场文书