最新公告
  • 欢迎您光临起源地模板网,本站秉承服务宗旨 履行“站长”责任,销售只是起点 服务永无止境!立即加入钻石VIP
  • 举例告诉你Python爬虫库urllib2怎么用

    正文概述    2020-10-23   223

    所谓网页抓取,就是把URL地址中指定的网络资源从网络流中读取出来,保存到本地。 在Python中有很多库可以用来抓取网页,先学习urllib2。

    举例告诉你Python爬虫库urllib2怎么用

    urllib2模块直接导入就可以用,在python3中urllib2被改为urllib.request

    使用urllib2,试了下用代理登陆拉取cookie,跳转抓图片......

    URLLIB2文档:http://docs.python.org/library/urllib2.html

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

    #!/usr/bin/python
    # -*- coding:utf-8 -*-
    # urllib2_test.py
    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()

    起源地下载网 » 举例告诉你Python爬虫库urllib2怎么用

    常见问题FAQ

    免费下载或者VIP会员专享资源能否直接商用?
    本站所有资源版权均属于原作者所有,这里所提供资源均只能用于参考学习用,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用者承担。更多说明请参考 VIP介绍。
    提示下载完但解压或打开不了?
    最常见的情况是下载不完整: 可对比下载完压缩包的与网盘上的容量,若小于网盘提示的容量则是这个原因。这是浏览器下载的bug,建议用百度网盘软件或迅雷下载。若排除这种情况,可在对应资源底部留言,或 联络我们.。
    找不到素材资源介绍文章里的示例图片?
    对于PPT,KEY,Mockups,APP,网页模版等类型的素材,文章内用于介绍的图片通常并不包含在对应可供下载素材包内。这些相关商业图片需另外购买,且本站不负责(也没有办法)找到出处。 同样地一些字体文件也是这种情况,但部分素材会在素材包内有一份字体下载链接清单。
    模板不会安装或需要功能定制以及二次开发?
    请QQ联系我们

    发表评论

    还没有评论,快来抢沙发吧!

    如需帝国cms功能定制以及二次开发请联系我们

    联系作者

    请选择支付方式

    ×
    迅虎支付宝
    迅虎微信
    支付宝当面付
    余额支付
    ×
    微信扫码支付 0 元