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
原创粉丝点击