zoukankan      html  css  js  c++  java
  • 爬虫之proxy(代理)

    proxy简介

    proxy即为代理,我们爬虫的时候肯定会有频繁访问某一网站的情况,这个时候有些服务器会识别到我们是非正常访问,就会把我们的IP禁掉,这个时候就需要用代理了。

    就好比现实生活中,我需要向A借一件东西,但是我跟A是仇人,直接向他借的话他不会借给我,这个时候我就让B帮我像A借,就说他要用,然后B借到东西之后再把东西给我用,这时,B就是我的代理了。

    常用的免费代理网站:http://www.goubanjia.com/。

    爬虫应该选择什么样的代理?

    • 针对不需要用户登录,cookie验证的网站,一般选择动态高匿代理。
    • 对于需要用户登录,身份认证的。一般选择静态IP

    使用proxy的步骤

    1. 设置代理地址
      proxy = {'http':'52.187.162.198:3128'}
    2. 创建ProxyHeader
      proxyHeader = request.ProxyHandler(proxy)
    3. 创建Opener
      opener = request.build_opener(proxyHeader)
    4. 安装Opener
      request.install_opener(opener)

    示例

    from urllib import request
    
    # 设置代理地址
    proxy = {'http':'52.187.162.198:3128'}
    
    # 创建ProxyHeader
    proxyHeader = request.ProxyHandler(proxy)
    
    # 创建Opener
    opener = request.build_opener(proxyHeader)
    
    # 安装Opener
    request.install_opener(opener)
    
    # 然后剩下的就跟正常使用差不多,只不过此时的request已经是绑定了代理之后的request
    url = 'https://www.taobao.com/'
    req = request.Request(url)
    response = request.urlopen(req)
    print(response.read().decode())
    

      

  • 相关阅读:
    欧拉公式
    isap的一些想法
    错误合集
    Hello World
    PAT (Advanced Level) Practice 1068 Find More Coins
    PAT (Advanced Level) 1087 All Roads Lead to Rome
    PAT (Advanced Level) 1075 PAT Judge
    PAT (Advanced Level) 1067 Sort with Swap(0, i)
    PAT (Advanced Level) 1017 Queueing at Bank
    PAT (Advanced Level) 1025 PAT Ranking
  • 原文地址:https://www.cnblogs.com/fu-yong/p/9018930.html
Copyright © 2011-2022 走看看