码迷,mamicode.com
首页 > 编程语言 > 详细

Urllib.request用法简单介绍(Python3.3)

时间:2015-05-04 21:39:52      阅读:216      评论:0      收藏:0      [点我收藏+]

标签:

Urllib.request用法简单介绍(Python3.3),有需要的朋友可以参考下。


urllib是Python标准库的一部分,包含urllib.request,urllib.error,urllib.parse,urlli.robotparser四个子模块,这里主要介绍urllib.request的一些简单用法.

首先是urlopen函数,用于打开一个URL:

 

# -*- coding:utf-8 -*- #获取并打印google首页的html
import urllib.request
response=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.request
handler=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.request
handler=urllib.request.ProxyHandler({‘http‘:‘http://someproxy.com:8080‘})
opener=urllib.request.build_opener(handler)
response=opener.open(‘http://www.google.com‘)
print(response.read())

 

Urllib.request用法简单介绍(Python3.3)

标签:

原文地址:http://www.cnblogs.com/Zidon/p/4477110.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!