urllib.request.urlopen()基本使用_CodingALife的博客-程序员秘密_request.urlopen

技术标签: python  Python基础详解  

1. urlopen( ) 方法

用于打开一个远程的url连接,并且向这个连接发出请求,获取响应结果。返回的结果是一个http响应对象,这个响应对象中记录了本次http访问的响应头和响应体

urllib.request.urlopen 参数介绍
urllib.request.urlopen(  url,   data=None,   [timeout, ]*,  cafile=None, capath=None, cadefault=False, context=None)

import urllib.request

url = 'https://www.python.org'
# 方式一
response = urllib.request.urlopen(url)
print(type(response))  # <class 'http.client.HTTPResponse'>
# 方式二
request = urllib.request.Request(url)
res = urllib.request.urlopen(url)
print(type(res))  # <class 'http.client.HTTPResponse'>

print(response.status)  # 200 获取响应状态码
print(response.reason)  # OK
print(response.version)  # 11
print(response)    # 获取响应,结果为:<http.client.HTTPResponse object at 0x10be801d0>
print(response.headers)   # 获取响应头
# Server: nginx
# Content-Type: text/html; charset=utf-8
# X-Frame-Options: DENY
# Via: 1.1 vegur
# Via: 1.1 varnish
# Content-Length: 48830
# Accept-Ranges: bytes
# Date: Thu, 12 Mar 2020 10:34:07 GMT
print(response.url)       # https://www.python.org  获取响应url
print(response.read())                  # 获取响应体 二进制字符串
print(response.read().decode("utf-8"))  # 对响应体进行解码
# 按行读取
print(response.readline())      # 读取一行
print(response.readline())      # 读取下一行
print(response.readlines())    # 读取多行。得到一个列表 每个元素是一行

通过结果可以发现response是一个HTTPResposne类型的对象,它主要包含的方法有read()、readinto()、getheader(name)、getheaders()、fileno()等函数和msg、version、status、reason、debuglevel、closed等属性。
例如response.read()就可以得到返回的网页内容,response.status就可以得到返回结果的状态码,如200代表请求成功,404代表网页未找到等。

2、添加data参数的时候就是以post请求方式请求,若没有data参数就是get请求方式

from urllib import request, parse

# 用parse模块,通过bytes(parse.urlencode())可以将post数据进行转换并放到
# urllib.request.urlopen的data参数中。这样就完成了一次post请求。
data = bytes(parse.urlencode({'word': 'hello'}), encoding='utf8')
response = request.urlopen('http://httpbin.org/post', data=data)
print(response.read())

3、timeout参数使用

在某些网络情况不好或者服务器端异常的情况会出现请求慢的情况,或者请求异常,所以这个时候我们需要给
请求设置一个超时时间,而不是让程序一直在等待结果。所以使用 timeout参数设置超时时间

import urllib.request

response = urllib.request.urlopen('http://httpbin.org/get', timeout=1)
print(response.read())   # 正常结束,控制台显示:socket.time : timed out
response = urllib.request.urlopen('http://httpbin.org/get', timeout=0.1)
print(response.read())   # 超时,控制台显示:urllib.error.URLErrot : <urlopen error timed out>

4、Request(url=url, data=data, method='POST') 方法

web开发中,同一个url往往可以对应若干套不同的数据(或者界面,如手机、电脑),后台可以根据发起请求的前端的用户代理的不同,而决定应该给前端做出什么样的响应,如果检测到没有用户代理可以拒绝访问。

有很多网站为了防止程序爬虫爬网站造成网站瘫痪,会需要携带一些headers头部信息才能访问,最长见的有user-agent参数所以需要伪装请求头,去访问目标站。

urllib.ruquest.Request 参数介绍:

           urllib.ruquest.Request(url=url,headers=headers,data=data,method='POST')

 headers 参数使用;给请求添加头部信息,定制自己请求网站时的头部信息,使得请求伪装成浏览器等终端

url = "http://www.baidu.com/"
req = request.Request(url=url, headers={'UserAgent':'Mozilla/5.0 (Windows NT 10.0; Win64;x64)AppleWebKit/537.36 (KHTML, likeGecko)Chrome/71.0.3578.80Safari/537.36'})
res = request.urlopen(req)  # 用加入了请求头的请求对象发起请求
print(res.status)           # 打印状态码

添加请求头的post请求方式

from urllib import request, parse

url = 'http://httpbin.org/post'
headers = {
            'User-Agent': 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)',
            'Host': 'httpbin.org'
          }
dict = {'name': 'taotao'}
data = bytes(parse.urlencode(dict), encoding='utf8')
req = request.Request(url=url, data=data, headers=headers, method='POST')
response = request.urlopen(req)
print(response.read().decode('utf-8'))

添加请求头的第二种post方式, 好处是自己可以定义一个请求头字典,然后循环进行添加

from urllib import request, parse

url = 'http://httpbin.org/post'
dict = {'name': 'Germey'}
data = bytes(parse.urlencode(dict), encoding='utf8')
req = request.Request(url=url, data=data, method='POST')
req.add_header('User-Agent', 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)')
response = request.urlopen(req)
print(response.read().decode('utf-8'))

5、urllib.parse模块 方法

url解析模块

1. urlparse( ) 方法 拆分url

URL解析函数侧重于将URL字符串拆分为其组件,或者将URL组件组合为URL字符串

拆分的时候协议类型部分就会是scheme=“ ”指定的部分。如果url里面已经带了协议,scheme指定的协议不会生效

urllib.parse.urlparse(urlstring, scheme=" ", allow_fragments=True)

urlparse("www.baidu.com/index.html;user?id=5#comment",scheme="https")

from urllib.parse import urlparse, urlunparse

# 对传入的url地址进行拆分; 可以用 scheme=“ ” 指定协议类型:
result = urlparse("http://www.baidu.com/index.html;user?id=5#comment")
print(result)
# ParseResult(scheme='http', netloc='www.baidu.com', path='/index.html',
# params='user', query='id=5', fragment='comment')

2. urlunparse( ) 方法  拼接url

功能和urlparse的功能相反,它是用于拼接 

data = ['http', 'www.baidu.com', 'index.html', 'user', 'a=123', 'commit']
print(urlunparse(data))  # http://www.baidu.com/index.html;user?a=123#commit

6. urlencode( ) 方法 

这个方法可以将字典转换为url参数

对url进行编码,因为urllib这个框架中的url中不能出现汉字,只能出现ascii码字符

from urllib import parse

url = "https://www.baidu.com/s?"
# 把参数写成字典的形式
dic = {"ie": "utf-8", "wd": "奔驰"}
# 用parse的urlencode方法编码
parames = parse.urlencode(dic)
# 将编码以后的参数拼接到url中
url += parames
print(request.urlopen(url=url))

参考:https://www.lagou.com/lgeduarticle/34376.html

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/mingyuli/article/details/104824709

智能推荐

Linux 的内存管理工具和调优参数_wowRicky的博客-程序员秘密

1. free2. top3. vmstat4. slabtop;5. pmap6. dmesg7. /proc/meminfo8. /proc/sys/vm 目录下的文件9. sync10./proc/zoneinfo 11./proc/pagetypeinfo查看内存工具:1.freefree - Display amount of free and used memory in the sy...

蒲公英x1可道云php,贝锐蒲公英与可道云合作:0门槛搭建私有云_731英语第一的博客-程序员秘密

公共网盘的上传、下载限速,文件安全性等问题,使得网盘的优势越来越少。因此,很多个人和企业都开始转向私有云,通过自建服务的方式来解决文件云端存储、同步、共享等需求。但是,部署私有云服务却拥有较高的门槛,不仅需要专门的电脑、主机作为服务器,而且远程访问还要固定公网IP,配置过程复杂繁琐,往往会耗费不少精力和财力。2018年11月23日,上海贝锐旗下的蒲公英异地组网路由器宣布与可道云(KodExplor...

webpack --搭建基础开发环境_cyadyx的博客-程序员秘密

webpack 搭建基础开发环境配置css配置js配置html配置图片配置文件1.css 打包配置把css抽离单独的文件(1)安装 mini-css-extract-pluginnpm install --save-dev mini-css-extract-plugin(2)plugin 中加入MiniCssExtractPlugin 并设置打包文件名const MiniCssExtractPlugin = require("mini-css-extract-plugin"

TensorFlow数据读取方法_倾城一少的博客-程序员秘密

转自:http://honggang.io/2016/08/19/tensorflow-data-reading/引言Tensorflow的数据读取有三种方式:Preloaded data: 预加载数据Feeding: Python产生数据,再把数据喂给后端。Reading from file: 从文件中直接读取这三种有读取方式有什么区别呢? 我们首

BUG : HTTP Status 500 - Request Parameter ‘xxxxXxx‘ not found. Available parameters are [qo, param1]_DYSLzx的博客-程序员秘密

错误信息HTTP Status 500 - Request processing failed; nested exception is org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.binding.BindingException: Parameter ‘plotId’ not found. Available parameters are [qo, param1]type Except

随便推点

mini6410基于linux2.6.36内核通过NFS启动根文件系统总结(四制作根文件系统及通过NFS挂载文件系统)_yinjiabin的博客-程序员秘密

本系列文章有本人yinjiabin制作,转载请注明出处:http://blog.csdn.net/yinjiabin/article/details/7489563根文件系统一般包括:1)基本的文件系统结构,包含一些必须的目录,比如:/dev,/proc,/bin,/etc,/lib,/usr,/tmp;2)基本程序运行所需的库函数,如:libc/uC-libc;3)基本的

webpack快速入门_reg183的博客-程序员秘密

生产环境作用:能让代码优化上线运行的环境,要注意文件大小优化,兼容等方面执行命令:npx webpack提取css成单独文件安装包# 指定版本,命令输入在一行npm i -D [email protected] [email protected] [email protected] [email protected] [email protected]#逐个依次安装npm i -D [email protected] npm i -D webpack.

快学Scala_博文视点的博客-程序员秘密

快学Scala(Core Java作者Horstmann最新力作)(美)霍斯曼(Horstmann,C.S.)著高宇翔译ISBN978-7-121-18567-02012年10月出版定价:79.00元16开408页内 容 简 介Scala是一门以Java虚拟机(JVM)为目标运行环境并将面向对象和函数式编程语言的最佳特性结合在一起的编程语言。你可以使用Sca

【自定义函数】销售订单跟踪报表 -- 获取已开票领料套数_issued qty_mqy1212的博客-程序员秘密

 /****** Object: UserDefinedFunction [dbo].[fn_SO_GetIssuedQty] Script Date: 12/11/2009 08:53:15 ******/SET ANSI_NULLS ONGO SET QUOTED_IDENTIFIER ONGO   /********************************** 销售订单跟