python中urllib.request和requests的使用及区别详解


Posted in Python onMay 05, 2020

urllib.request

我们都知道,urlopen()方法能发起最基本对的请求发起,但仅仅这些在我们的实际应用中一般都是不够的,可能我们需要加入headers之类的参数,那需要用功能更为强大的Request类来构建了

在不需要任何其他参数配置的时候,可直接通过urlopen()方法来发起一个简单的web请求

发起一个简单的请求

import urllib.request
url='https://www.douban.com'
webPage=urllib.request.urlopen(url)
print(webPage)
data=webPage.read()
print(data)
print(data.decode('utf-8'))

urlopen()方法返回的是一个http.client.HTTPResponse对象,需要通过read()方法做进一步的处理。一般使用read()后,我们需要用decode()进行解码,通常为utf-8,经过这些步骤后,最终才获取到我们想要的网页。

添加Headers信息

import urllib.request
url='https://www.douban.com'
headers = {
   'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36',
 }
response=urllib.request.Request(url=url,headers=headers)
webPage=urllib.request.urlopen(response)
print(webPage.read().decode('utf-8'))

使用Request类返回的又是一个urllib.request.Request对象了。

通常我们爬取网页,在构造http请求的时候,都需要加上一些额外信息,什么Useragent,cookie等之类的信息,或者添加代理服务器。往往这些都是一些必要的反爬机制

requests

通常而言,在我们使用python爬虫时,更建议用requests库,因为requests比urllib更为便捷,requests可以直接构造get,post请求并发起,而urllib.request只能先构造get,post请求,再发起。

import requests
url='https://www.douban.com'
headers = {
  'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36',
}
get_response = requests.get(url,headers=headers,params=None)
post_response=requests.post(url,headers=headers,data=None,json=None)
print(post_response)
print(get_response.text)
print(get_response.content)
print(get_response.json)

get_response.text得到的是str数据类型。

get_response.content得到的是Bytes类型,需要进行解码。作用和get_response.text类似。

get_response.json得到的是json数据。

总而言之,requests是对urllib的进一步封装,因此在使用上显得更加的便捷,建议小伙伴们在实际应用当中尽量使用requests。

补充知识:python中urllib.request.Request()与urllib.request.urlopen()区别

蟒蛇中urllib.request.Request()与urllib.request.urlopen()的区别:

相对于urllib.request.urlopen()来说urllib.request.Request是进一步的包装请求,下面是请求类的源码示例:

class Request:
  
  # 主要看这块,构造函数中指明了Request进一步包装请求中可以传递的参数有(url,data,headers,            
  # origin_req_host,unverifiable,method)
 
  def __init__(self, url, data=None, headers={},
         origin_req_host=None, unverifiable=False,
         method=None):
    self.full_url = url
    self.headers = {}
    self.unredirected_hdrs = {}
    self._data = None
    self.data = data
    self._tunnel_host = None
    for key, value in headers.items():
      self.add_header(key, value)
    if origin_req_host is None:
      origin_req_host = request_host(self)
    self.origin_req_host = origin_req_host
    self.unverifiable = unverifiable
    if method:
      self.method = method
  pass

我们可以这样使用(以下是模拟有道字典翻译发送的请求):

# 请求地址url
url = "http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule"
 
# 请求头
request_headers = {
  'Host':'fanyi.youdao.com',
  "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36",
}
 
# 发送给服务器的表单
form_data = {
  "i": word,
  "from": "AUTO",
  "to": "AUTO",
  "smartresult": "dict",
  "doctype": "json",
  "version": "2.1",
  "keyfrom": "fanyi.web",
  "action": "FY_BY_REALTIME",
  "typoResult": "false"
}
 
# POST发送的data必须为bytes或bytes类型的可迭代对象,不能是字符串
form_data = urllib.parse.urlencode(form_data).encode()
 
# 构造请求对象Request
req = urllib.request.Request(url, data=form_data, headers=request_headers)
 
# 发起请求
response = urllib.request.urlopen(req)
data = response.read().decode()
print(data)

所以,总的来说,如果我们在获取请求对象时,不需要过多的参数传递,我么可以直接选择urllib.request.urlopen();如果需要进一步的包装请求,则需要用urllib.request里。的urlopen()进行包装处理。

以上这篇python中urllib.request和requests的使用及区别详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python3.x和Python2.x的区别介绍
Feb 12 Python
Python中列表、字典、元组、集合数据结构整理
Nov 20 Python
用Python编写web API的教程
Apr 30 Python
利用python批量检查网站的可用性
Sep 09 Python
玩转python selenium鼠标键盘操作(ActionChains)
Apr 12 Python
python使用tornado实现登录和登出
Jul 28 Python
Python 中的lambda函数介绍
Oct 10 Python
Python操作远程服务器 paramiko模块详细介绍
Aug 07 Python
在TensorFlow中屏蔽warning的方式
Feb 04 Python
python+opencv3生成一个自定义纯色图教程
Feb 19 Python
Python爬虫:从m3u8文件里提取小视频的正确操作
May 14 Python
Python Flask搭建yolov3目标检测系统详解流程
Nov 07 Python
python requests包的request()函数中的参数-params和data的区别介绍
May 05 #Python
关于Python解包知识点总结
May 05 #Python
python 使用事件对象asyncio.Event来同步协程的操作
May 04 #Python
在python里使用await关键字来等另外一个协程的实例
May 04 #Python
python 异步async库的使用说明
May 04 #Python
Python插件机制实现详解
May 04 #Python
python3+selenium获取页面加载的所有静态资源文件链接操作
May 04 #Python
You might like
CI框架验证码CAPTCHA辅助函数用法实例
2014/11/05 PHP
php实现的ping端口函数实例
2014/11/12 PHP
php获取网页里所有图片并存入数组的方法
2015/04/06 PHP
Zend Framework连接Mysql数据库实例分析
2016/03/19 PHP
EXTJS内使用ACTIVEX控件引起崩溃问题的解决方法
2010/03/31 Javascript
jQuery 淡入淡出 png图在ie8下有黑色边框的解决方法
2013/03/05 Javascript
弹出窗口并且此窗口带有半透明的遮罩层效果
2014/03/13 Javascript
利用a标签自动解析URL分析网址实例
2014/10/20 Javascript
JavaScript变量声明详解
2014/11/27 Javascript
浅谈nodeName,nodeValue,nodeType,typeof 的区别
2015/01/13 Javascript
JavaScript中函数表达式和函数声明及函数声明与函数表达式的不同
2015/11/15 Javascript
原生js页面滚动延迟加载图片
2015/12/20 Javascript
Bootstrap表单组件教程详解
2016/04/26 Javascript
微信小程序 按钮滑动的实现方法
2017/09/27 Javascript
详解使用Typescript开发node.js项目(简单的环境配置)
2017/10/09 Javascript
使用Promise封装小程序wx.request的实现方法
2019/11/13 Javascript
Vue.js实现立体计算器
2020/02/22 Javascript
[43:58]DOTA2上海特级锦标赛C组败者赛 Newbee VS Archon第二局
2016/02/27 DOTA
Python实现备份文件实例
2014/09/16 Python
Python实现处理管道的方法
2015/06/04 Python
Python变量作用范围实例分析
2015/07/07 Python
Python Nose框架编写测试用例方法
2017/10/26 Python
高质量Python代码编写的5个优化技巧
2017/11/16 Python
python3.6.3安装图文教程 TensorFlow安装配置方法
2020/06/24 Python
python使用matplotlib画饼状图
2018/09/25 Python
python判断计算机是否有网络连接的实例
2018/12/15 Python
用Python实现大文本文件切割的方法
2019/01/12 Python
Python3.5实现的三级菜单功能示例
2019/03/25 Python
计算机二级python学习教程(1) 教大家如何学习python
2019/05/16 Python
python psutil模块使用方法解析
2019/08/01 Python
django echarts饼图数据动态加载的实例
2019/08/12 Python
centos7中安装python3.6.4的教程
2019/12/11 Python
Python  Asyncio模块实现的生产消费者模型的方法
2021/03/01 Python
FC-Moto丹麦:欧洲最大的摩托车服装和头盔商店之一
2019/08/20 全球购物
家长评语和期望
2014/02/10 职场文书
网吧温馨提示
2015/07/17 职场文书