zoukankan      html  css  js  c++  java
  • python使用代理ip

    python使用代理的方法有两种

    1.

     1 #先创建代理ip对象
     2 proxy_support = urllib.request.ProxyHandler({'https':'117.64.149.137:808'})
     3 
     4 #定制一个opener对象
     5 opener = urllib.request.build_opener(proxy_support)
     6 
     7 #安装这个opener对象,以后的urlopen就一直使用这个代理地址了
     8 urllib.request.install_opener(opener)
     9 
    10 #发出请求时,就是用到这个代理地址了
    11 html = urllib.request.urlopen('xxxxxxxxxx').read()

    2.

    1 #先创建代理ip对象
    2 proxy_support = urllib.request.ProxyHandler({'https':'117.64.149.137:808'})
    3 
    4 #定制一个opener对象
    5 opener = urllib.request.build_opener(proxy_support)
    6 
    7 #这里可以直接使用opener对象发出请求
    8 html = opener.open('xxxxxxxxx').read() 

    示例代码:

     1 import urllib.request
     2 
     3 #这一段三句话是为了请求时带上浏览器标识,因为有的网站看到是爬虫的标识直接返回403
     4 #请求的网站不涉及到提交数据,所以没有给出data参数
     5 url = 'https://whatismyipaddress.com/'
     6 header = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36'}
     7 req = urllib.request.Request(url,headers=header)
     8 
     9 #使用代理和还原不使用代理的方法
    10 #if语句相当于一个开关,不要写成True
    11 use_proxy = urllib.request.ProxyHandler({'https':'117.64.149.137:808'})
    12 null_proxy = urllib.request.ProxyHandler()
    13 if True:
    14     opener = urllib.request.build_opener(use_proxy)
    15 else:
    16     opener = urllib.request.build_opener(null_proxy)
    17 #根据上面的开关,安装的opener对象是否带有代理地址
    18 urllib.request.install_opener(opener)
    19 
    20 #获取返回结果
    21 #同时可以使用html = opener.open(req).read()获取结果
    22 html = urllib.request.urlopen(req).read()
    23 
    24 #这网页返回页面的内容太多,在控制台不好查看,
    25 #并且返回的内容是二进制格式,可以直接写入文件,当个网页查看
    26 with open('E:\whatismyip.html','wb') as file:
    27     file.write(html)
    28     print('OK')

      

      

    初学linux,每学到一点东西就写一点,如有不对的地方,恳请包涵!
  • 相关阅读:
    存储过程中执行动态Sql语句
    SqlServer新建视图
    DataGridView DataGridViewCheckBoxColumn编辑时实时触发事件
    oracle number 和sqlserver numeric的区别
    放下你的无效社交
    一个程序员眼中的北京和上海
    10+年程序员总结的20+条经验教训
    SQL collate
    SQL自定义函数split分隔字符串
    C# .NET开发Oracle数据库应用程序
  • 原文地址:https://www.cnblogs.com/forlive/p/11308742.html
Copyright © 2011-2022 走看看