python 爬虫 批量获取代理ip的实例代码

yipeiwu_com7年前Python爬虫

实例如下所示:

import urllib.request
import os, re,sys,time
try:
 from StringIO import StringIO
except ImportError:
 from io import StringIO
loca = re.compile(r"""ion":"\D+", "ti""")
#伪装成浏览器
header = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36'}
class Getip():
 def __init__(self,diqu):
  self.ur ={"xicidaili国内普通代理 --1线":"http://www.xicidaili.com/nt/",
        
    "ip84国内普通代理 --2线":'http://www.ip84.com/dlpn-http/',
        
    'xicidaili国内高匿名代理 --1线':'http://www.xicidaili.com/nn/',
       
    'ip84国内高匿名代理 --2线':'http://www.ip84.com/dlgn-http/',
    
    'xicidaili国外高匿名代理 --1线':'http://www.xicidaili.com/wn/',
    
    'ip84国外高匿名代理 --2线':'http://www.ip84.com/gwgn-http/',
    'xicidaili国外普通代理 --1线':'http://www.xicidaili.com/wt/',
    'haodailiip国内混合代理 --3线':'http://www.haodailiip.com/guonei/',
    'haodailiip国外混合代理 --3线':'http://www.haodailiip.com/guoji/',
        }
  self.diqu = diqu
 
 def urlopen(self,url):
  global header
  try:
   req = urllib.request.Request(url, None, header)
   res=urllib.request.urlopen(req)
  
   return res
  except:
   pass
 def getip(self,ren):
  '''url = "http://proxy.ipcn.org/proxylist.html"#代理IP页面
  ip_proxy_re = re.compile(r"""\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d{1,}""")# 直接匹配 xxx.xxx.xxx.xxx:xxxx'''
  
  url = self.ur[self.diqu]+str(ren)
  
  ip_proxy_re = re.compile(r'(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s*</td>\s*<td>\s*(\d{1,})\s*</td>\s*<[^\u4E00-\u9FA5]+>([\u4E00-\u9FA5]*\s*[\u4E00-\u9FA5]*\s*[\u4E00-\u9FA5]*)\s*<')
  #################################通用正则匹配的  格式 是  (IP,端口,地区) 地区有可能包含换行和空格
  try:
   data = self.urlopen(url).read().decode('utf-8')
  except:
   return None
  
  self.rel = []
  
  ip = ip_proxy_re.findall(data)
  ##########返回的IP 就是 正则匹配的结果(IP,端口,地区) 地区有可能包含换行和空格
  
  return ip
  
if __name__ == '__main__':
 g=Getip("xicidaili国内普通代理 --1线")
 import pprint
 for x in range(4):
  ips = g.getip(1)
  print('获取到ip地址一共:',len(ips))
  pprint.pprint(ips)

以上这篇python 爬虫 批量获取代理ip的实例代码就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python爬虫 urllib模块发起post请求过程解析

python爬虫 urllib模块发起post请求过程解析

urllib模块发起的POST请求 案例:爬取百度翻译的翻译结果 1.通过浏览器捉包工具,找到POST请求的url 针对ajax页面请求的所对应url获取,需要用到浏览器的捉包工具。...

python3之微信文章爬虫实例讲解

前提: python3.4 windows 作用:通过搜狗的微信搜索接口http://weixin.sogou.com/来搜索相关微信文章,并将标题及相关链接导入Excel表格中 说明:...

解决Python3 抓取微信账单信息问题

这段时间有个朋友想导出微信里面的账单信息,后来发现微信的反爬虫还是很厉害的,花了点时间去分析。 一、采用传统模拟http抓取 抓取的主要URL:https://wx.tenpay.com...

python爬虫 猫眼电影和电影天堂数据csv和mysql存储过程解析

字符串常用方法 # 去掉左右空格 'hello world'.strip() # 'hello world' # 按指定字符切割 'hello world'.split(' ')...

Python爬取十篇新闻统计TF-IDF

Python爬取十篇新闻统计TF-IDF

统计十篇新闻TF-IDF 统计TF-IDF词频,每篇文章的 top10 的高频词存储为 json 文件 TF-IDF TF-IDF(term frequency–inverse docu...