代理ip池

代理ip池

from bs4 import BeautifulSoup
 +from selenium import webdriver
 +import subprocess as sp
 +from lxml import etree
 +import requests
 +import random
 +import re
 +
 +"""
 +函数说明:获取IP代理
 +Parameters:
 +	page - 高匿代理页数,默认获取第一页
 +Returns:
 +	proxys_list - 代理列表
 +Modify:
 +	2017-05-27
 +"""
 +def get_proxys(page = 1):
 +	#requests的Session可以自动保持cookie,不需要自己维护cookie内容
 +	S = requests.Session()
 +	#西祠代理高匿IP地址
 +	target_url = 'http://www.xicidaili.com/nn/%d' % page
 +	#完善的headers
 +	target_headers = {'Upgrade-Insecure-Requests':'1',
 +		'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36',
 +		'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
 +		'Referer':'http://www.xicidaili.com/nn/',
 +		'Accept-Encoding':'gzip, deflate, sdch',
 +		'Accept-Language':'zh-CN,zh;q=0.8',
 +	}
 +	#get请求
 +	target_response = S.get(url = target_url, headers = target_headers)
 +	#utf-8编码
 +	target_response.encoding = 'utf-8'
 +	#获取网页信息
 +	target_html = target_response.text
 +	#获取id为ip_list的table
 +	bf1_ip_list = BeautifulSoup(target_html, 'lxml')
 +	bf2_ip_list = BeautifulSoup(str(bf1_ip_list.find_all(id = 'ip_list')), 'lxml')
 +	ip_list_info = bf2_ip_list.table.contents
 +	#存储代理的列表
 +	proxys_list = []
 +	#爬取每个代理信息
 +	for index in range(len(ip_list_info)):
 +		if index % 2 == 1 and index != 1:
 +			dom = etree.HTML(str(ip_list_info[index]))
 +			ip = dom.xpath('//td[2]')
 +			port = dom.xpath('//td[3]')
 +			protocol = dom.xpath('//td[6]')
 +			proxys_list.append(protocol[0].text.lower() + '#' + ip[0].text + '#' + port[0].text)
 +	#返回代理列表
 +	return proxys_list
 +
 +"""
 +函数说明:检查代理IP的连通性
 +Parameters:
 +	ip - 代理的ip地址
 +	lose_time - 匹配丢包数
 +	waste_time - 匹配平均时间
 +Returns:
 +	average_time - 代理ip平均耗时
 +Modify:
 +	2017-05-27
 +"""
 +def check_ip(ip, lose_time, waste_time):
 +	#命令 -n 要发送的回显请求数 -w 等待每次回复的超时时间(毫秒)
 +	cmd = "ping -n 3 -w 3 %s"
 +	#执行命令
 +	p = sp.Popen(cmd % ip, stdin=sp.PIPE, stdout=sp.PIPE, stderr=sp.PIPE, shell=True) 
 +	#获得返回结果并解码
 +	out = p.stdout.read().decode("gbk")
 +	#丢包数
 +	lose_time = lose_time.findall(out)
 +	#当匹配到丢失包信息失败,默认为三次请求全部丢包,丢包数lose赋值为3
 +	if len(lose_time) == 0:
 +		lose = 3
 +	else:
 +		lose = int(lose_time[0])
 +	#如果丢包数目大于2个,则认为连接超时,返回平均耗时1000ms
 +	if lose > 2:
 +		#返回False
 +		return 1000
 +	#如果丢包数目小于等于2个,获取平均耗时的时间
 +	else:
 +		#平均时间
 +		average = waste_time.findall(out)
 +		#当匹配耗时时间信息失败,默认三次请求严重超时,返回平均好使1000ms
 +		if len(average) == 0:
 +			return 1000
 +		else:
 +			#
 +			average_time = int(average[0])
 +			#返回平均耗时
 +			return average_time
 +
 +"""
 +函数说明:初始化正则表达式
 +Parameters:
 +	无
 +Returns:
 +	lose_time - 匹配丢包数
 +	waste_time - 匹配平均时间
 +Modify:
 +	2017-05-27
 +"""
 +def initpattern():
 +	#匹配丢包数
 +	lose_time = re.compile(u"丢失 = (\d+)", re.IGNORECASE)
 +	#匹配平均时间
 +	waste_time = re.compile(u"平均 = (\d+)ms", re.IGNORECASE)
 +	return lose_time, waste_time
 +
 +if __name__ == '__main__':
 +	#初始化正则表达式
 +	lose_time, waste_time = initpattern()
 +	#获取IP代理
 +	proxys_list = get_proxys(1)
 +
 +	#如果平均时间超过200ms重新选取ip
 +	while True:
 +		#从100个IP中随机选取一个IP作为代理进行访问
 +		proxy = random.choice(proxys_list)
 +		split_proxy = proxy.split('#')
 +		#获取IP
 +		ip = split_proxy[1]
 +		#检查ip
 +		average_time = check_ip(ip, lose_time, waste_time)
 +		if average_time > 200:
 +			#去掉不能使用的IP
 +			proxys_list.remove(proxy)
 +			print("ip连接超时, 重新获取中!")
 +		if average_time < 200:
 +			break
 +
 +	#去掉已经使用的IP
 +	proxys_list.remove(proxy)
 +	proxy_dict = {split_proxy[0]:split_proxy[1] + ':' + split_proxy[2]}
 +	print("使用代理:", proxy_dict)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Scrapy是一个强大的Python爬虫框架,可以用于抓取和提取网页数据。如果你想在Scrapy中使用代理IP,可以按照以下步骤进行: 1. 首先,你需要准备一个代理IP。这可以是一个存储代理IP的数据库或者一个包含代理IP列表的文件。 2. 在Scrapy的项目中,你可以创建一个中间件来处理代理IP。中间件可以在请求发送之前或之后修改请求。你可以创建一个自定义的中间件类,在其中实现代理IP的设置。 例如,你可以创建一个名为ProxyMiddleware的中间件类,并在其中实现process_request方法,从代理IP中随机选择一个代理IP,并将其设置为请求的代理。 ```python class ProxyMiddleware(object): def process_request(self, request, spider): # 从代理IP中随机选择一个代理IP proxy = get_proxy_ip() request.meta['proxy'] = proxy ``` 3. 将中间件添加到Scrapy的配置中。在项目的settings.py文件中,找到DOWNLOADER_MIDDLEWARES配置项,并将你的中间件类添加到其中。 ```python DOWNLOADER_MIDDLEWARES = { 'your_project_name.middlewares.ProxyMiddleware': 543, # 其他中间件... } ``` 4. 现在,当Scrapy发送请求时,中间件会在请求前设置代理IP。这样,你就可以使用代理IP来爬取网页数据了。 请注意,使用代理IP需要注意合法性和稳定性。你需要确保代理IP有效,并及时更新代理IP,以免影响爬虫的正常运行。另外,使用代理IP时也需要遵守网站的相关规定,避免对目标网站造成不必要的干扰。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值