代理:破解封IP这种反爬机制。
什么是代理:
----代理服务器。
代理的作用:
----突破自身ip访问的限制。
----隐藏自身真实IP
代理相关的网站:
----快代理
----西祠代理
-----www.goubaijia.com
代理ip类型:
http://www.goubanjia.com/ #代理ip
-http: 应用到http协议对应的url中
-https: 应用到https协议对应的url中
代理ip匿名度:
-----透明:服务器知道该次请求使用了代理,也知道请求对应的真实ip
----匿名:知道使用了代理,不知道真实ip
----高匿:不知道使用了代理,更不知道真实ip
#反爬机制: 封ip
#反反爬策略:使用代理进行请求发送
Ip地址查询:http://ip.293.net/
以下是相关代码:
import requests
url = 'http://ip.293.net/'
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.87 Safari/537.36 SE 2.X MetaSr 1.0'
}
page_text = requests.get(url=url,headers=headers,proxies={"http":'http://115.46.80.150:8123'}).text
with open('ip.html','w',encoding='utf-8') as fp:
fp.write(page_text)
其实你只要注意看,就会发现其实是在get请求里面加了一个proxies={“http”:‘http://115.46.80.150:8123’},这就是ip代理的精髓。
更高级一点的代码是在“goubaijia”网站上看到的线程的ip代理:
import requests;
import time;
import threading;
import urllib3;
ips = [];
# 爬数据的线程类
class CrawlThread(threading.Thread):
def __init__(self,proxyip):
super(CrawlThread, self).__init__();
self.proxyip=proxyip;
def run(self):
# 开始计时
start = time.time();
#消除关闭证书验证的警告
urllib3.disable_warnings();
#使用代理IP请求网址,注意第三个参数verify=False意思是跳过SSL验证(可以防止报SSL错误)
html=requests.get(url=targetUrl, proxies={"http" : 'http://' + self.proxyip, "https" : 'https://' + self.proxyip}, verify=False, timeout=15).content.decode()
# 结束计时
end = time.time();
# 输出内容
print(threading.current_thread().getName() + "使用代理IP, 耗时 " + str(end - start) + "毫秒 " + self.proxyip + " 获取到如下HTML内容:\n" + html + "\n*************")
# 获取代理IP的线程类
class GetIpThread(threading.Thread):
def __init__(self,fetchSecond):
super(GetIpThread, self).__init__();
self.fetchSecond=fetchSecond;
def run(self):
global ips;
while True:
# 获取IP列表
res = requests.get(apiUrl).content.decode()
# 按照\n分割获取到的IP
ips = res.split('\n');
# 利用每一个IP
for proxyip in ips:
if proxyip.strip():
# 开启一个线程
CrawlThread(proxyip).start();
# 休眠
time.sleep(self.fetchSecond);
if __name__ == '__main__':
# 这里填写无忧代理IP提供的API订单号(请到用户中心获取)
order = "d6eaa6dd0f1dce497bb0eb5f7b4cb92f";
# 获取IP的API接口
apiUrl = "http://dynamic.goubanjia.com/dynamic/get/" + order + ".html";
# 要抓取的目标网站地址
targetUrl = "http://pv.sohu.com/cityjson?ie=utf-8";
# 获取IP时间间隔,建议为5秒
fetchSecond = 5;
# 开始自动获取IP
GetIpThread(fetchSecond).start();
以上我都试过,不过第一段测出来的还是自己的ip,而第二个会动态出来很多,不过花了我0.1元。呜呜~~(白嫖失败了)
于是乎,我又去找了免费ip代理网:
添加链接描述
希望大家代理成功~~~~