Python3网络爬虫教程5——ProxyHandler处理(代理服务器和代理IP)

版权声明:本文章为沐言-BigTree原创,转载复制请标明出处 https://blog.csdn.net/u011318077/article/details/86538042

上接:
Python3网络爬虫教程4——UserAgent的使用(用户伪装)(附常用的UserAgent值清单
[https://blog.csdn.net/u011318077/article/details/86508095]

3. ProxyHandler处理(代理服务器)

  • 使用代理IP,是爬虫的常用手段
  • 服务器有反爬虫手段,使用代理就是反反爬虫
  • 获取代理服务器的地址:
  • 代理用了隐藏真实的访问,代理也不允许频繁的访问某一个固定的网址,
  • 所以代理IP一定要很多很多,然后更换不同的IP访问
  • 基本使用步骤:
    • 设置代理地址
    • 创建ProxyHandler
    • 创建Opener
    • 安装Opener
    • 看案例43_10
      43_10
# 使用代理IP访问一个网站
# 选取一个不上的网站,防止IP被封,以后访问不了
# 网址:http://www.cnqiang.com/
# 免费代理IP网站:http://www.goubanjia.com/


from urllib import request, error

if __name__ == '__main__':

    url = 'http://www.cnqiang.com/'

    # 使用代理的步骤
    # 1.设置代理IP,进入代理网站选择一个IP:PORT
    proxy = {'http': '47.97.190.145:9999'}
    # 2.创建ProxyHandler
    proxy_handler = request.ProxyHandler(proxy)
    # 3.创建Opener
    opener = request.build_opener(proxy_handler)
    # 4.安装Opener
    request.install_opener(opener)

    # 现在如果访问url,就会使用代理服务器
    try:
        rsp = request.urlopen(url)
        html = rsp.read().decode()
        print(html)
    except error.URLError as e:
        print(e)
    except error.HTTPError as e:
        print(e)
    except Exception as e:
        print(e)

下接:
Python3网络爬虫教程6——cookie & session(cookie的属性,保存及模块的使用)

猜你喜欢

转载自blog.csdn.net/u011318077/article/details/86538042
今日推荐