使用urllib
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的更多相关文章
- python urllib
在伴随学习爬虫的过程中学习了解的一些基础库和方法总结扩展 1. urllib 在urllib.request module中定义下面的一些方法 urllib.request.urlopen(url,d ...
- Python3使用urllib访问网页
介绍 改教程翻译自python官网的一篇文档. urllib.request是一个用于访问URL(统一资源定位符)的Python模块.它以urlopen函数的形式提供了一个非常简单的接口,可以访问使用 ...
- 爬虫初探(1)之urllib.request
-----------我是小白------------ urllib.request是python3自带的库(python3.x版本特有),我们用它来请求网页,并获取网页源码. # 导入使用库 imp ...
- python 3.x urllib学习
urllib.request import urllib.request as ur url='http://ie.icoa.cn' user_agent = 'Mozilla/4.0 (compat ...
- Python爬虫学习(1): urllib的使用
1.urllib.urlopen 打开一个url的方法,返回一个文件对象,然后可以进行类似文件对象的操作 In [1]: import urllibIn [2]: file = urllib.urlo ...
- python2 与 python3 urllib的互相对应关系
urllib Python2 name Python3 nameurllib.urlopen() Deprecated. See urllib.request.urlopen() which mirr ...
- urllib+BeautifulSoup无登录模式爬取豆瓣电影Top250
对于简单的爬虫任务,尤其对于初学者,urllib+BeautifulSoup足以满足大部分的任务. 1.urllib是Python3自带的库,不需要安装,但是BeautifulSoup却是需要安装的. ...
- 初学python之urllib
urllib.request urlopen()urllib.urlopen(url, data, proxies) :创建一个表示远程url的类文件对象,然后像本地文件一样操作这个类文件对象来获取远 ...
- urllib.urlretrieve的用法
urllib.urlretrieve(url, local, cbk) urllib.urlretrieve(p,'photo/%s.jpg'%p.split('/')[-4]) url要下载的网站 ...
- 关于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 ...
随机推荐
- [Qt] QlineEdit 限制输入,例如只能输入整数
要注意validor的作用域,如果超出作用域,则会无效.例如下面的代码,在UI的类的构造函数里.所以要new一个validtor. QIntValidator *intValidator = new ...
- Spring Boot中的Properties
文章目录 简介 使用注解注册一个Properties文件 使用属性文件 Spring Boot中的属性文件 @ConfigurationProperties yaml文件 Properties环境变量 ...
- 《名侦探柯南》动画登陆bilibili
不管你看没看过.喜不喜欢,也一定听说过<名侦探柯南>这部动画,它和<火影>.<海贼王>几部动画陪伴了一代人成长的道路,而且<名侦探柯南>还是这几部动画中 ...
- mac OS vi/vim 使用教程
vi/vim 的使用 基本上 vi/vim 共分为三种模式 分别是 命令模式(Command mode) 输入模式(Insert mode) 底线命令模式(Last line mode) 命令模式: ...
- 交换机上的MAC地址表
拓扑图: 1.首先在R1上的配置: R1(config)#int R1(config)#interface g R1(config)#interface gigabitEthernet 0/0 R1( ...
- web前端项目中遇到的一些问题总结(08.23更新)
个人网站 https://iiter.cn 程序员导航站 开业啦,欢迎各位观众姥爷赏脸参观,如有意见或建议希望能够不吝赐教! 写一些最近工作中Vue项目中遇到的问题. 巴啦啦小魔仙,污卡拉,全身变,小 ...
- 开启Apache服务出现的错误
httpd: Could not reliably determine the server's fully qualified domain name, using 127.0.0.1 for Se ...
- Clickhouse 时区转换(下)
Clickhouse 时区转换续—时区参数转换 天天加班,时间不够,主要还是我太懒,流汗,,,,,,另外如果这篇学习笔记超过100阅读量并有评论,我可能半夜也会爬起来更新的. 相信大家看我之前记录的这 ...
- 从零开始配置webpack(基于webpack 4 和 babel 7版本)
webpack 核心概念: Entry: 入口 Module:模块,webpack中一切皆是模块 Chunk:代码库,一个chunk由十多个模块组合而成,用于代码合并与分割 Loader:模块转换器, ...
- Codeforce 140C (贪心+优先队列)补题
C. New Year Snowmen time limit per test2 seconds memory limit per test256 megabytes inputstandard in ...
