python的urllib库

最简单的urllib2打开一个网页

import urllib2
response = urllib2.urlopen('http://www.baidu.com/')
html = response.read()
print html

然后我们可以使用一个Request对象

import urllib2  
req = urllib2.Request('http://www.baidu.com')  
response = urllib2.urlopen(req)  
the_page = response.read()  
print the_page

post数据的情况

import urllib  
import urllib2  

url = 'http://www.someserver.com/register.cgi'  
  
values = {'name' : 'WHY',  
          'location' : 'SDU',  
          'language' : 'Python' }  

data = urllib.urlencode(values) # 编码工作
req = urllib2.Request(url, data)  # 发送请求同时传data表单
response = urllib2.urlopen(req)  #接受反馈的信息
the_page = response.read()  #读取反馈的内容

加上http头

import urllib2
request = urllib2.Request('http://www.baidu.com/')
request.add_header('User-Agent', 'fake-client')
response = urllib2.urlopen(request)
print response.read()

查看cookies

import urllib2
import cookielib
cookie = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))
response = opener.open('http://www.baidu.com')
for item in cookie:
    print 'Name = '+item.name
    print 'Value = '+item.value

PUT或者DELETE方法

import urllib2
request = urllib2.Request(uri, data=data)
request.get_method = lambda: 'PUT' # or 'DELETE'
response = urllib2.urlopen(request)

如果没有传送data参数,urllib2使用GET方式的请求。其实get请求可以直接去构造url的字符串

异常处理  注意有URLError和HTTPError HTTPError是URLError的子类

import urllib2  
  
req = urllib2.Request('http://www.baibai.com')  
  
try: urllib2.urlopen(req)  
  
except urllib2.URLError, e:    
    print e.reason
#这个是http状态码
print e.code

geturl()函数是获取可能存在跳转的网页的真实地址

from urllib2 import Request, urlopen, URLError, HTTPError


old_url = 'http://rrurl.cn/b1UZuP'
req = Request(old_url)
response = urlopen(req)  
print 'Old url :' + old_url
print 'Real url :' + response.geturl()

info()是页面的http头信息

from urllib2 import Request, urlopen, URLError, HTTPError

old_url = 'http://www.baidu.com'
req = Request(old_url)
response = urlopen(req)  
print 'Info():'
print response.info()
http应答状态码
200:请求成功      处理方式:获得响应的内容,进行处理 
201:请求完成,结果是创建了新资源。新创建资源的URI可在响应的实体中得到    处理方式:爬虫中不会遇到 
202:请求被接受,但处理尚未完成    处理方式:阻塞等待 
204:服务器端已经实现了请求,但是没有返回新的信 息。如果客户是用户代理,则无须为此更新自身的文档视图。    处理方式:丢弃
300:该状态码不被HTTP/1.0的应用程序直接使用, 只是作为3XX类型回应的默认解释。存在多个可用的被请求资源。    处理方式:若程序中能够处理,则进行进一步处理,如果程序中不能处理,则丢弃
301:请求到的资源都会分配一个永久的URL,这样就可以在将来通过该URL来访问此资源    处理方式:重定向到分配的URL
302:请求到的资源在一个不同的URL处临时保存     处理方式:重定向到临时的URL 
304 请求的资源未更新     处理方式:丢弃 
400 非法请求     处理方式:丢弃 
401 未授权     处理方式:丢弃 
403 禁止     处理方式:丢弃 
404 没有找到     处理方式:丢弃 
5XX 回应代码以“5”开头的状态码表示服务器端发现自己出现错误,不能继续执行请求    处理方式:丢弃

参考  http://blog.csdn.net/column/details/why-bug.html

原文地址:https://www.cnblogs.com/virusdefender/p/3450125.html