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. SQLI-LABS学习笔记(一)

    逼话少说,如有错误,烦请指出,谢谢. 第一关 提示传个id的参数 后面跟个单引号 http://10.2.10.31/sqli/Less-1/?id=1’ 发现报错,这里看到是已经闭合了 You ha ...

  2. What does __GNUC__ mean?

    It indicates that I'm a GNU compiler and you can use GNU extensions. https://stackoverflow.com/quest ...

  3. Windows API Index

    https://docs.microsoft.com/en-us/windows/desktop/apiindex/windows-api-list

  4. phper:敢问路在何方

    很多php程序员存在未来发展方面的困扰,介于各方面的因素,phper 比其他程序员更容易遇到上升天花板. 一方面,一般只有初创企业为了快速实现产品上市以及极容易招到 phper 才使用 php 来实现 ...

  5. Lambda表达式最佳实践

    简介 Lambda表达式java 8引入的函数式编程框架.之前的文章中我们也讲过Lambda表达式的基本用法. 本文将会在之前的文章基础上更加详细的讲解Lambda表达式在实际应用中的最佳实践经验. ...

  6. java中interrupt,interrupted和isInterrupted的区别

    文章目录 isInterrupted interrupted interrupt java中interrupt,interrupted和isInterrupted的区别 前面的文章我们讲到了调用int ...

  7. vue2.x学习笔记(二十七)

    接着前面的内容:https://www.cnblogs.com/yanggb/p/12682364.html. 单元测试 vue cli拥有开箱即用的通过jest或mocha进行单元测试的内置选项.官 ...

  8. pip安装openvc-python国内镜像源

    采用清华大学的镜像源. pip install -i https://pypi.tuna.tsinghua.edu.cn/simple --trusted-host pypi.tuna.tsinghu ...

  9. 【Linux常见命令】split命令

    split - split a file into pieces 按照指定的行数或大小分割文件 语法: split [OPTION]... [INPUT [PREFIX]] Output fixed- ...

  10. 与IBM的Lin Sun关于Istio 1.0和微服务的问答

    北京时间 7 月 31 日,Istio 正式发布了 1.0 版本,并表示已经可用于生产环境.该版本的主要新特性包括跨集群 mesh 支持.细粒度流量控制以及在一个 mesh 中增量推出 mutual ...