在网上看到我们可以通过抓取一些提供免费代理IP的网站,来使用代理IP,可以怎么样来抓取呢?下面IP精灵来给大家介绍一个方法,大家可以参考看看,以下是操作代码:
#coding=utf-8
import re
import urllib.request
import urllib.parse
import os
from urllib.error import URLError,HTTPError
url='http://www.kuaidaili.com/ops/' #http://www.xicidaili.com/ http://www.proxy360.cn/default.aspx http://www.kuaidaili.com/ops/
headers={'Accept':'text/html,application/xhtml+xm…plication/xml;q=0.9,*/*;q=0.8',
'Accept-Encoding':'gzip,deflate',
'Accept-Language':'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',
'Host':'fs.xicidaili.com',
'Cookie':'Hm_lvt_0cf76c77469e965d2957f0553e6ecf59=1511441689,1511784134,1511785760; Hm_lpvt_0cf76c77469e965d2957f0553e6ecf59=1511785760',
'Connection':'keep-alive',
'User-Agent':'Mozilla/5.0 (Windows NT 6.1; W…) Gecko/20100101 Firefox/57.0'
}
headers=urllib.parse.urlencode(headers).encode('utf8')
rep=urllib.request.Request(url,headers)
reponse=urllib.request.urlopen(rep)
html=reponse.read().decode(encoding='UTF-8')
reg=r'\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b'
ip_list=re.findall(reg,html)
print(ip_list)
f=open('ip.txt','a')
f.write(str(ip_list)+'\n')
f.close()
这样我们就能够把网站上面提供的免费IP抓取来使用了,但是要注意免费IP的质量比较不稳定,需要经过检测才可以使用。