python requests更换代理适用于IP频率限制的方法

yipeiwu_com6年前Python基础

有些网址具有IP限制,比如同一个IP一天只能点赞一次。

解决方法就是更换代理IP。

从哪里获得成千上万的IP呢? 百度“http代理” 可获得一大堆网站。

比如某代理网站,1天6元,可以无限提取。

把提取的IP,保存到txt文件中。

写一个方法,读取文件,存入数组中

def getProxysFromFile():
 with open("proxy.txt", "r") as f:
  l = f.readlines()
 return l

比如执行某任务,传入单个代理IP+PORT

def run(proxy):
 
 try:
  print("proxy:{}".format(proxy))
  s=requests.Session()
  proxies={
  "http": "http://{}".format(proxy.strip()), "https":"https://{}".format(proxy.strip())
  }
  header={
   "Host":"www.xxx.com",
   "Referer":"http://www.xxx.com/xxx.html?199",
   "User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36"
 
  }
  ret=s.get(url="http://www.xxx.com/data/dz?uid=199&ztype=1",headers=header,proxies=proxies,timeout=4)
  rc=ret.content.decode("utf-8")
  print(rc)
  if "成功" in rc:
   global count
   count+=1
   print(count)
 except:
  pass

接下来就是调度,简单写了个调度,比如每隔5秒钟,启动100个线程去执行。(这里为了简单,在上面的run中设置了超时时间为4秒,所以能保证不会导致启动的线程太多未完成卡死)

if __name__ == '__main__':
 count=1
 l=getProxysFromFile()
 while True:
  for i in range(100):
   try:
    t=threading.Thread(target=run,args=(l.pop(),))
    t.start()
   except:
    pass
  time.sleep(5)

效果如下,速度还是很快的。

以上这篇python requests更换代理适用于IP频率限制的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

在PyCharm下使用 ipython 交互式编程的方法

目的:方便调试,查看中间结果,因为觉得设断点调试相对麻烦。 【运行环境:macOS 10.13.3,PyCharm 2017.2.4】 老手: 选中代码行,Alt+Shift+E。 或选...

Python读写文件模式和文件对象方法实例详解

Python读写文件模式和文件对象方法实例详解

本文实例讲述了Python读写文件模式和文件对象方法。分享给大家供大家参考,具体如下: 一. 读写文件模式 利用open() 读写文件时,将会返回一个 file 对象,其基本语法格式如...

python中反射用法实例

本文实例讲述了python中反射用法。分享给大家供大家参考。具体如下: import sys, types,new def _get_mod(modulePath): try:...

python3中利用filter函数输出小于某个数的所有回文数实例

我就废话不多说了,直接上代码吧! def _int_iter(): """根据回文数的定义。首先生成一个从0开始的整数无限序列""" n = 0 while True:...

python 实现一次性在文件中写入多行的方法

将要写入的内容 构造 进一个list 中,使用writelines()方法 一次性写入。 file_w.writelines(list) file_w.flush() file.c...