Python urllib、urllib2、httplib抓取网页代码实例

 更新时间:2015年05月09日 10:02:38   投稿:junjie  
这篇文章主要介绍了Python urllib、urllib2、httplib抓取网页代码实例,本文直接给出demo代码,代码中包含详细注释,需要的朋友可以参考下

使用urllib2,太强大了
试了下用代理登陆拉取cookie,跳转抓图片......
文档:http://docs.python.org/library/urllib2.html

直接上demo代码了
包括:直接拉取,使用Reuqest(post/get),使用代理,cookie,跳转处理

#!/usr/bin/python
# -*- coding:utf-8 -*-
# urllib2_test.py
# author: wklken
# 2012-03-17 wklken@yeah.net


import urllib,urllib2,cookielib,socket

url = "http://www.testurl....." #change yourself
#最简单方式
def use_urllib2():
 try:
  f = urllib2.urlopen(url, timeout=5).read()
 except urllib2.URLError, e:
  print e.reason
 print len(f)

#使用Request
def get_request():
 #可以设置超时
 socket.setdefaulttimeout(5)
 #可以加入参数 [无参数,使用get,以下这种方式,使用post]
 params = {"wd":"a","b":"2"}
 #可以加入请求头信息,以便识别
 i_headers = {"User-Agent": "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.1) Gecko/20090624 Firefox/3.5",
       "Accept": "text/plain"}
 #use post,have some params post to server,if not support ,will throw exception
 #req = urllib2.Request(url, data=urllib.urlencode(params), headers=i_headers)
 req = urllib2.Request(url, headers=i_headers)

 #创建request后,还可以进行其他添加,若是key重复,后者生效
 #request.add_header('Accept','application/json')
 #可以指定提交方式
 #request.get_method = lambda: 'PUT'
 try:
  page = urllib2.urlopen(req)
  print len(page.read())
  #like get
  #url_params = urllib.urlencode({"a":"1", "b":"2"})
  #final_url = url + "?" + url_params
  #print final_url
  #data = urllib2.urlopen(final_url).read()
  #print "Method:get ", len(data)
 except urllib2.HTTPError, e:
  print "Error Code:", e.code
 except urllib2.URLError, e:
  print "Error Reason:", e.reason

def use_proxy():
 enable_proxy = False
 proxy_handler = urllib2.ProxyHandler({"http":"http://proxyurlXXXX.com:8080"})
 null_proxy_handler = urllib2.ProxyHandler({})
 if enable_proxy:
  opener = urllib2.build_opener(proxy_handler, urllib2.HTTPHandler)
 else:
  opener = urllib2.build_opener(null_proxy_handler, urllib2.HTTPHandler)
 #此句设置urllib2的全局opener
 urllib2.install_opener(opener)
 content = urllib2.urlopen(url).read()
 print "proxy len:",len(content)

class NoExceptionCookieProcesser(urllib2.HTTPCookieProcessor):
 def http_error_403(self, req, fp, code, msg, hdrs):
  return fp
 def http_error_400(self, req, fp, code, msg, hdrs):
  return fp
 def http_error_500(self, req, fp, code, msg, hdrs):
  return fp

def hand_cookie():
 cookie = cookielib.CookieJar()
 #cookie_handler = urllib2.HTTPCookieProcessor(cookie)
 #after add error exception handler
 cookie_handler = NoExceptionCookieProcesser(cookie)
 opener = urllib2.build_opener(cookie_handler, urllib2.HTTPHandler)
 url_login = "https://www.yourwebsite/?login"
 params = {"username":"user","password":"111111"}
 opener.open(url_login, urllib.urlencode(params))
 for item in cookie:
  print item.name,item.value
 #urllib2.install_opener(opener)
 #content = urllib2.urlopen(url).read()
 #print len(content)
#得到重定向 N 次以后最后页面URL
def get_request_direct():
 import httplib
 httplib.HTTPConnection.debuglevel = 1
 request = urllib2.Request("http://www.google.com")
 request.add_header("Accept", "text/html,*/*")
 request.add_header("Connection", "Keep-Alive")
 opener = urllib2.build_opener()
 f = opener.open(request)
 print f.url
 print f.headers.dict
 print len(f.read())

if __name__ == "__main__":
 use_urllib2()
 get_request()
 get_request_direct()
 use_proxy()
 hand_cookie()

您可能感兴趣的文章:

相关文章

  • Anaconda修改默认虚拟环境安装位置的方案分享

    Anaconda修改默认虚拟环境安装位置的方案分享

    新安装Anaconda后,在创建环境时环境自动安装在C盘,但是C盘空间有限,下面这篇文章主要给大家介绍了关于Anaconda修改默认虚拟环境安装位置的相关资料,需要的朋友可以参考下
    2023-01-01
  • python 进程池pool使用详解

    python 进程池pool使用详解

    这篇文章主要介绍了python 进程池pool使用的相关资料,帮助大家更好的理解和学习python进程,感兴趣的朋友可以了解下
    2020-10-10
  • 在python中,使用scatter绘制散点图的实例

    在python中,使用scatter绘制散点图的实例

    今天小编就为大家分享一篇在python中,使用scatter绘制散点图的实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-07-07
  • Python文件遍历os.walk()与os.listdir()使用及说明

    Python文件遍历os.walk()与os.listdir()使用及说明

    这篇文章主要介绍了Python文件遍历os.walk()与os.listdir()使用及说明,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-11-11
  • Python之求任意正整数的阶乘方式

    Python之求任意正整数的阶乘方式

    这篇文章主要介绍了Python之求任意正整数的阶乘方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-08-08
  • Python常用内置模块之xml模块(详解)

    Python常用内置模块之xml模块(详解)

    下面小编就为大家带来一篇Python常用内置模块之xml模块(详解)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-05-05
  • Python使用文件操作实现一个XX信息管理系统的示例

    Python使用文件操作实现一个XX信息管理系统的示例

    这篇文章主要介绍了Python使用文件操作实现一个XX信息管理系统的示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-07-07
  • python爬虫之requests库的使用详解

    python爬虫之requests库的使用详解

    这篇文章主要为大家介绍了python爬虫之requests库的使用,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助
    2021-11-11
  • 在Python的Flask框架下收发电子邮件的教程

    在Python的Flask框架下收发电子邮件的教程

    这篇文章主要介绍了在Python的Flask框架下收发电子邮件的教程,主要用到了Flask中的Flask-mail工具,需要的朋友可以参考下
    2015-04-04
  • Appium Python自动化测试之环境搭建的步骤

    Appium Python自动化测试之环境搭建的步骤

    这篇文章主要介绍了Appium Python自动化测试之环境搭建的步骤,以32位的Windows 7操作系统为例介绍Appium+Python的环境搭建步骤,感兴趣的小伙伴们可以参考一下
    2019-01-01

最新评论