urllib2使用总结

urllib2库是涉及到url资源请求的常用库

官方文档:urllib2 — extensible library for opening URLs

常用函数:

urllib2.urlopen(url [, data [, timeout ][, cafile][, capath][, cadefault ][, context ])

url:可以是string,也可以是Request对象

timeout:设置请求超时

返回的对象有geturl()、info()、read()方法

geturl()方法获取连接地址

info()方法获取返回网页信息

read()方法获取返回网页内容

例子:

import urllib2

url = 'http://www.csdn.net/'

html = urllib2.urlopen(url, timeout=5)

urllib2.Request(url [, data][, headers][, origin_req_host][, unverifiable])

url:为合法的url,string

headers:浏览器头

例子:

import urllib2

url="http://www.csdn.net/"

headers = {"User-Agent":"Mozilla/4.0;MSTE 6.0; Windows NT 5.1"}
req = urllib2.Request(url, headers=headers)

html = urllib2.urlopen(req)


错误处理:

URLError

import urllib2

try:
    html = urllib2.urlopen("http://www.csdn.net/")
except urllib2.URLError, e:
    print e.reason

HTTPError

import urllib2

try:
    html = urllib2.urlopen("http://www.csdn.net")
except urllib2.HTTPError, e:
    print e.code
    print e.reason
SocketError

import socket

try:
    html = urllib2.urlopen("http://www.csdn.net")
except urllib2.SocketError, e:
    print e.reason

连接超时捕获

import urllib2  
import socket  
      
try:  
    urllib2.urlopen("http://example.com", timeout = 1)  
except urllib2.URLError, e:  
    if isinstance(e.reason, socket.timeout):  
        print "There was an error: %r" % e




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值