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

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())
原文地址:https://www.cnblogs.com/Zidon/p/4477110.html