urlopen的基本用法:

工具为:python3(windows)

其完整表达式为:

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

1、发出一个请求.打开bttpbin.org网页,此处为get方式的请求类型

>>>import urllib.request 
>>> response = urllib.request.urlopen("http://httpbin.org")

#此处为将 结果赋值给response
>>> print(response.read().decode('utf-8'))

#得到的response是bytes类型,所以我们需要使用decode

httpbin.org:可以以后用来做http测试

2、此处为POST 类型的请求需要使用到data

>>> import urllib.parse
>>> import urllib.request
>>> data = bytes(urllib.parse.urlencode({"word":"hello"}),encoding="utf8")

#需要创建data参数,需要为bytes类型,用urlencode将字典传过去
>>> response = urllib.request.urlopen("http://httpbin.org/post",data = data)
>>> print(response.read())

3、超时设置timeout

>>> import urllib.request
>>> response = urllib.request.urlopen("http://httpbin.org/get",timeout=1 )
>>> print(response.read())

发现下方有正常的响应

若超时的时间为0.1,如果出现异常,对异常进行捕获

>>> import socket
>>> import urllib.request
>>> import urllib.error

try:
response = urllib.request.urlopen("http://httpbin.org/get",timeout=0.1)
except urllib.error.URLError as e:
if isinstance(e.reason,socket.timeout):
print("TIME OUT")

会出现TIME  OUT 结果。

发送请求之后出现响应

1、响应类型

>>> import urllib.request
>>> response = urllib.request.urlopen("http://httpbin.org")
>>> print(type(response))
<class 'http.client.HTTPResponse'>

2、状态码 响应头

>>> import urllib.request
>>> response =urllib.request.urlopen("http://httpbin.org")
>>> print(response.status)   #此处为状态码,200显示为成功的意思
200
>>> print(response.getheaders()) #此处为获取所有的状态头,并且以元组的形式输出
[('Connection', 'close'), ('Server', 'gunicorn/19.9.0'), ('Date', 'Tue, 09 Oct 2018 12:49:34 GMT'), ('Content-Type', 'text/html; charset=utf-8'), ('Content-Length', '10122'), ('Access-Control-Allow-Origin', '*'), ('Access-Control-Allow-Credentials', 'true'), ('Via', '1.1 vegur')]

>>> print(response.getheader('Server'))
gunicorn/19.9.0

[此处表示为此处的服务器是由gunicorn/19.9.0所做]
response.read():获取响应体内容为bytes类型,我们可以用decode进行转化

>>> import urllib.request
>>> response = urllib.request.urlopen("http://httpbin.org")
>>> print(response.read().decode('utf-8'))

Request的基本用法

(如果我们想要发送header对象或者其他复杂东西,就需要用到Request)

>>> import urllib.request
>>> response = urllib.request.Request("http://httpbin.org")

>>> response = urllib.request.urlopen(request)

>>> print(response.read().decode('utf-8'))
正常输出,与上方直接输入的结果是完全一致,有了Request能够更加方便

此处为模仿火狐浏览器进行请求

from urllib import request,parse
url = "http://httpbin.org/post"
headers = {
"User-Agent":'Mozllia/4.0(compatible;MSIE 5.5;Windows NT)',
"Host":'httpbin.org'
}
dict = {
'name':'Germey'
}
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"))

也会出现结果

使用urllib的更多相关文章

  1. python urllib

    在伴随学习爬虫的过程中学习了解的一些基础库和方法总结扩展 1. urllib 在urllib.request module中定义下面的一些方法 urllib.request.urlopen(url,d ...

  2. Python3使用urllib访问网页

    介绍 改教程翻译自python官网的一篇文档. urllib.request是一个用于访问URL(统一资源定位符)的Python模块.它以urlopen函数的形式提供了一个非常简单的接口,可以访问使用 ...

  3. 爬虫初探(1)之urllib.request

    -----------我是小白------------ urllib.request是python3自带的库(python3.x版本特有),我们用它来请求网页,并获取网页源码. # 导入使用库 imp ...

  4. python 3.x urllib学习

    urllib.request import urllib.request as ur url='http://ie.icoa.cn' user_agent = 'Mozilla/4.0 (compat ...

  5. Python爬虫学习(1): urllib的使用

    1.urllib.urlopen 打开一个url的方法,返回一个文件对象,然后可以进行类似文件对象的操作 In [1]: import urllibIn [2]: file = urllib.urlo ...

  6. python2 与 python3 urllib的互相对应关系

    urllib Python2 name Python3 nameurllib.urlopen() Deprecated. See urllib.request.urlopen() which mirr ...

  7. urllib+BeautifulSoup无登录模式爬取豆瓣电影Top250

    对于简单的爬虫任务,尤其对于初学者,urllib+BeautifulSoup足以满足大部分的任务. 1.urllib是Python3自带的库,不需要安装,但是BeautifulSoup却是需要安装的. ...

  8. 初学python之urllib

    urllib.request urlopen()urllib.urlopen(url, data, proxies) :创建一个表示远程url的类文件对象,然后像本地文件一样操作这个类文件对象来获取远 ...

  9. urllib.urlretrieve的用法

    urllib.urlretrieve(url, local, cbk) urllib.urlretrieve(p,'photo/%s.jpg'%p.split('/')[-4]) url要下载的网站 ...

  10. 关于python3.X 报"import urllib.request ImportError: No module named request"错误,解决办法

    #encoding:UTF-8 import urllib.request url = "http://www.baidu.com" data = urllib.request.u ...

随机推荐

  1. 一些软件的 Basic Auth 行为

    一个 WBEM 在2003年的bug I'm trying to access the WBEM service of the CIMOM on the ESX Server 3i and all m ...

  2. 素数&欧拉函数

    素数表 const int maxN找[1,maxN)内的素数 int prime[int I]第I个素数 const int maxN=1e5+5; int prime[maxN]; bool ma ...

  3. OC的消息机制简单介绍

    在OC的消息机制中主要分为三个阶段,分别为: 1.消息发送阶段:从类以及父类的方法缓存列表和方法列表查找方法. 2.动态解析阶段:在消息发送阶段没有找到方法,则会进入这个阶段,负责动态添加方法实现. ...

  4. vue2.x学习笔记(二十九)

    接着前面的内容:https://www.cnblogs.com/yanggb/p/12682822.html. 路由 官方路由 对于大多数的单页面应用,都推荐使用官方支持的vue-router库. 从 ...

  5. JS实现元素的全屏、退出全屏功能

     在实际开发中,我们很可能需要实现某一元素的全屏和退出全屏功能,如canvas.所幸的是,js提供了相关api用来处理这一问题,只需简单的调用requestFullScreen.exitFullScr ...

  6. 如何把字符串数组从 Swift 传递给 C

    作者:Natasha The Robot,原文链接,原文日期:2016-10-27译者:BigbigChai:校对:walkingway:定稿:CMB Swift 允许我们将原生的字符串直接传递给一个 ...

  7. CodeForces - 1102B Array K-Coloring

    B. Array K-Coloring time limit per test2 seconds memory limit per test256 megabytes inputstandard in ...

  8. Makefile中的CFLAGS,LDFLAGS,LIBS

    CFLAGS:C编译器选项,而CXXFLAGS表示C++编译器的选项 1. CFLAGS参数 选项 说明 -c 用于把源码编译成.o对象文件,不进行链接过程 -o 用于连接生成可执行文件,在其后可以指 ...

  9. Jmeter简单压测之服务器监控

    此篇为最近工作需要到内容,故现在做一个总结. 最近家里电脑坏了,等待会公司空闲在编写. 文章构思中,敬请期待.......

  10. 如何找到Hive提交的SQL相对应的Yarn程序的applicationId

    最近的工作是利用Hive做数据仓库的ETL转换,大致方式是将ETL转换逻辑写在一个hsql文件中,脚本当中都是简单的SQL语句,不包含判断.循环等存储过程中才有的写法,仅仅支持一些简单的变量替换,比如 ...