Python urllib,urllib2,httplib 使用

需求:

抓取网页,解析获取内容

涉及库:【重点urllib2】

urllib   http://docs.python.org/library/urllib.html

urllib2  http://docs.python.org/library/urllib2.html

httplib   http://docs.python.org/library/httplib.html

使用urllib:

1.      抓取网页信息

urllib.urlopen(url[, data[, proxies]]) :

url: 表示远程数据的路径

data: 以post方式提交到url的数据

proxies:用于设置代理

urlopen返回对象提供方法:

-         read() , readline() ,readlines() , fileno() , close() :这些方法的使用方式与文件对象完全一样

-         info():返回一个httplib.HTTPMessage对象,表示远程服务器返回的头信息

-         getcode():返回Http状态码。如果是http请求,200请求成功完成;404网址未找到

-         geturl():返回请求的url

使用:

[python] view plaincopyprint?
 
  1. #!/usr/bin/python  
  2. # -*- coding:utf-8 -*-  
  3. # urllib_test.py  
  4. # author:wklken  
  5. # 2012-03-17  wklken#yeah.net   
  6.   
  7. import os  
  8. import urllib  
  9. url = "http://www.siteurl.com"  
  10.   
  11. def use_urllib():  
  12.   import urllib, httplib  
  13.   httplib.HTTPConnection.debuglevel = 1   
  14.   page = urllib.urlopen(url)  
  15.   print "status:", page.getcode() #200请求成功,404  
  16.   print "url:", page.geturl()  
  17.   print "head_info: ",  page.info()  
  18.   print "Content len:", len(page.read())  

附带的其他方法:(主要是url编码解码)

-         urllib.quote(string[, safe]):对字符串进行编码。参数safe指定了不需要编码的字符

-         urllib.unquote(string) :对字符串进行解码

-          urllib.quote_plus(string [ , safe ] ) :与urllib.quote类似,但这个方法用'+'来替换' ',而quote用'%20'来代替' '

-          urllib.unquote_plus(string ) :对字符串进行解码

-         urllib.urlencode(query[, doseq]):将dict或者包含两个元素的元组列表转换成url参数。例如 字典{'name': 'wklken', 'pwd': '123'}将被转换为"name=wklken&pwd=123"

-         urllib.pathname2url(path):将本地路径转换成url路径

-          urllib.url2pathname(path):将url路径转换成本地路径

使用:

[python] view plaincopyprint?
 
  1. def urllib_other_functions():  
  2.   astr = urllib.quote('this is "K"')  
  3.   print astr  
  4.   print urllib.unquote(astr)  
  5.   bstr = urllib.quote_plus('this is "K"')  
  6.   print bstr  
  7.   print urllib.unquote(bstr)  
  8.   
  9.   params = {"a":"1""b":"2"}  
  10.   print urllib.urlencode(params)  
  11.   
  12.   l2u = urllib.pathname2url(r'd:a est.py')  
  13.   print l2u   
  14.   print urllib.url2pathname(l2u)  



2.  下载远程数据

urlretrieve方法直接将远程数据下载到本地

urllib.urlretrieve(url[, filename[, reporthook[, data]]]):

filename指定保存到本地的路径(若未指定该,urllib生成一个临时文件保存数据)

reporthook回调函数,当连接上服务器、以及相应的数据块传输完毕的时候会触发该回调

data指post到服务器的数据

该方法返回一个包含两个元素的元组(filename, headers),filename表示保存到本地的路径,header表示服务器的响应头。

[python] view plaincopyprint?
 
    1. def  callback_f(downloaded_size, block_size, romote_total_size):  
    2.   per = 100.0 * downloaded_size * block_size / romote_total_size  
    3.   if per > 100:  
    4.     per = 100   
    5.   print "%.2f%%"% per   
    6.   
    7. def use_urllib_retrieve():  
    8.   import urllib  
    9.   local = os.path.join(os.path.abspath("./"), "a.html")  
    10.   print local  
    11.   urllib.urlretrieve(url,local,callback_f)  
原文地址:https://www.cnblogs.com/lps365/p/3318226.html