Urllib.request用法简单介绍(Python3.3)
来源:互联网 发布:青岛seo是什么 编辑:程序博客网 时间:2024/06/09 17:36
urllib是Python标准库的一部分,包含urllib.request,urllib.error,urllib.parse,urllib.robotparser四个子模块,这里主要介绍urllib.request的一些简单用法.
首先是urlopen函数,用于打开一个URL:
# -*- coding:utf-8 -*- #获取并打印google首页的htmlimport urllib.requestresponse=urllib.request.urlopen('http://www.google.com')html=response.read()print(html)
urlopen返回一个类文件对象,可以像文件一样操作,同时支持一下三个方法:
- info():返回一个对象,表示远程服务器返回的头信息。
- getcode():返回Http状态码,如果是http请求,200表示请求成功完成;404表示网址未找到。
- geturl():返回请求的url地址。
有时候我们需要设置代理,这时我们可以这样做:
# -*- coding:utf-8 -*- #设置全局代理import urllib.requesthandler=urllib.request.ProxyHandler({'http':'http://someproxy.com:8080'})opener=urllib.request.build_opener(handler)urllib.request.install_opener(opener)#安装opener作为urlopen()使用的全局URL opener,即以后调用urlopen()时都会使用安装的opener对象。response=urllib.request.urlopen('http://www.google.com')print(response.read())
如果要细致的设置代理,可以用opener的open方法打开URL:
# -*- coding:utf-8 -*- #设置代理import urllib.requesthandler=urllib.request.ProxyHandler({'http':'http://someproxy.com:8080'})opener=urllib.request.build_opener(handler)response=opener.open('http://www.google.com')print(response.read())
打开url后,我们可以将内容写入一个本地文件来达到保存网页的目的,但是这里有一个更方便的方法,那就是调用urlretrieve():
# -*- coding:utf-8 -*- #使用urllib.request.urlretrieve()将网页保存到本地import urllib.requesturl='http://www.baidu.com/'local_path='P:\\download.html'urllib.request.urlretrieve(url, local_path)
1 0
- Urllib.request用法简单介绍(Python3.3)
- 【转】Urllib.request用法简单介绍(Python3.3)
- python 自带urllib.request 模块简单介绍(python3.5)
- python3.3中urllib.request.open问题
- python3 urllib.request
- Python3:urllib.request详解
- python3 标准库 urllib.request
- Python3: urllib.request 的使用
- urllib.request.Request的用法
- Python3中urllib使用介绍
- python3 urllib.request抓资源的方式
- python3 urllib.request 按行处理
- python3的urllib的request模块
- Python3中urllib.request.retrieve的使用
- python3 urllib.request 网络请求操作
- Python3.3中的urllib
- python urllib简单用法
- 在python3.3后urllib2已经不能再用,只能用urllib.request来代替
- ClippingNode裁切节点
- 将ffmpeg移植到Android
- 努力+运气。。。。
- QT多线程
- projecteuler---->problem=7----10001st prime
- Urllib.request用法简单介绍(Python3.3)
- SQL 中 where 1=1 和 1=0的 作用
- oj学生类
- pythonchallenge level6--python2.7
- 如藕片32藕片【1】 哦irewo瑞文去餓
- Java复习第四天---IO流
- WPF学习笔记——为BUTTON添加背景图片
- Base: ACID外的另外一种选择
- 服务器-nginx-方向代理配置