爬蟲第一步!就是搭建代理池!不然一封你IP!你還爬個錘子!

代理是什麼?

代理實際上就是代理服務器, 代理服務器的工作機制很象我們生活中常常提及的代理商,假設你的機器為A機,你想獲得的數據由B機提供,代理服務器為C機,那麼具體的連接過程是這樣的。 首先,A機需要B機的數據,它與C機建立連接,C機接收到A機的數據請求後,與B機建立連接,下載A機所請求的B機上的數據到本地,再將此數據發送至A機,完成代理任務。如圖(圖片有點醜):

爬蟲第一步!就是搭建代理池!不然一封你IP!你還爬個錘子!

為什麼要使用代理?

我們在做爬蟲的過程中經常會遇到這樣的情況,最初爬蟲正常運行,正常抓取數據,一切看起來都是那麼美好,然而一杯茶的功夫可能就會出現錯誤,比如403 Forbidden,這時候打開網頁一看,可能會看到“您的IP訪問頻率太高”這樣的提示。出現這種現象的原因是網站採取了一些反爬蟲措施。比如,服務器會檢測某個IP在單位時間內的請求次數,如果超過了這個閾值,就會直接拒絕服務,返回一些錯誤信息,這種情況可以稱為封IP。

這時候代理的作用就來了, 你封我的ip,我用代理以後,使用代理ip來請求數據最後返回給我,你沒轍了吧,哈哈!!廢話不多說,進入正題!

動態代理ip

動態代理,顧名思義,會變化的ip。通過撥號vps來實現。

VPS服務器,即VPS(VirtualPrivateServer虛擬專用服務器)技術,將部服務器分割成多個虛擬專享服務器的優質服務。每個VPS都可分配獨立公網IP地址、獨立操作系統、獨立超大空間、獨立內存、獨立CPU資源、獨立執行程序和獨立系統配置等。用戶除了可以分配多個虛擬主機及無限企業郵箱外,更具有獨立服務器功能,可自行安裝程序,單獨重啟服務器。通俗的來說,VPS服務器也就是虛擬的專用服務器,用戶並接觸不到物理上的機器,也不需要機器的物理硬件等設施負責維護等。

撥號vps服務器在vps服務器的基礎原理 上添加了一個動態換IP的功能,行駛不定期更換用戶的功能,常用與投票,刷單,批量註冊微博,批量註冊QQ等,所有你能想到使用IP的服務器,有很多人用這種功能搶手機搶票你能想到用IP賺錢的方式應該都是用的上。

撥號vps架設動態代理服務器

爬蟲第一步!就是搭建代理池!不然一封你IP!你還爬個錘子!

進群:960410445 一起交流 小編手把手教你搭建代理詞 你截圖給我就好!

在購買撥號vps的時候,選擇預裝centos7系統,這裡還附帶了撥號軟件pppoe。(沒有的話聯繫服務商裝好)

下面來配置pppoe:

[root@localhost ~]# pppoe-setup     #進入配置
Welcome to the PPPoE client setup. First, I will run some checks on
your system to make sure the PPPoE client is installed properly...
LOGIN NAME
Enter your Login Name (default root):     #輸入寬帶賬號
INTERFACE
Enter the Ethernet interface connected to the PPPoE modem
For Solaris, this is likely to be something like /dev/hme0.
For Linux, it will be ethX, where 'X' is a number.
(default eth0): #回車跳過就可以了,默認使用eth0網卡,ifconfig可以查看網卡信息
Do you want the link to come up on demand, or stay up continuously?
If you want it to come up on demand, enter the idle time in seconds
after which the link should be dropped. If you want the link to
stay up permanently, enter 'no' (two letters, lower-case.)
NOTE: Demand-activated links do not interact well with dynamic IP
addresses. You may have some problems with demand-activated links.
Enter the demand value (default no): no  #這裡詢問的是,adsl連接以後,是否持續保持連接。或者是自動的斷開,在指定的時間(以秒數計算)內。多數情況下,我們希望手動的打開關閉連接。所以這裡選擇默認的no。
DNS
Please enter the IP address of your ISP's primary DNS server.
If your ISP claims that 'the server will provide dynamic DNS addresses',
enter 'server' (all lower-case) here.
If you just press enter, I will assume you know what you are

doing and not modify your DNS setup.
Enter the DNS information here: #DNS設置,回車跳過
PASSWORD
Please enter your Password:     #輸如寬帶密碼
Please re-enter your Password:     #再次輸入
USERCTRL
Please enter 'yes' (three letters, lower-case.) if you want to allow
normal user to start or stop DSL connection (default yes): yes  #是否允許普通用戶啟用/關閉 ADSL連接。默認是允許。
FIREWALLING
Please choose the firewall rules to use. Note that these rules are
very basic. You are strongly encouraged to use a more sophisticated
firewall setup; however, these will provide basic security. If you
are running any servers on your machine, you must choose 'NONE' and
set up firewalling yourself. Otherwise, the firewall rules will deny
access to all standard servers like Web, e-mail, ftp, etc. If you
are using SSH, the rules will block outgoing SSH connections which
allocate a privileged source port.
The firewall choices are:
0 - NONE: This/> for ensuring the security of your machine. You are STRONGLY
recommended to use some kind of firewall rules.
1 - STANDALONE: Appropriate for a basic stand-alone web-surfing workstation
2 - MASQUERADE: Appropriate for a machine acting as an Internet gateway
for a LAN
Choose a type of firewall (0-2): 0    #防火牆選項。這裡提供的防火牆可以給你提供基本的安全保護。我不推薦你使用----你最好選擇“NONE”選項0。無論是什麼樣的用戶使用,我都建議你使用額外的工具來配置防火牆規則(iptables目前看來是一個非常不錯的工具)。
  
Start this connection at boot time
Do you want to start this connection at boot time?
Please enter no or yes (default no):yes    #是否在開機時,打開這個連接?
** Summary of what you entered **
Ethernet Interface: eth0
User name: 123456
Activate-on-demand: No
DNS: Do not adjust
Firewalling: NONE
User Control: yes
Accept these settings and adjust configuration files (y/n)? y  #所有的配置信息填寫完成之後,系統將給出一個報告,完整的顯示出你輸入的配置信息。如果,你確信你輸入的配置信息是正確的,輸入yes寫入配置文件。輸入no放棄配置。

Adjusting /etc/sysconfig/network-scripts/ifcfg-ppp0
Adjusting /etc/ppp/chap-secrets and /etc/ppp/pap-secrets
(But first backing it up to /etc/ppp/chap-secrets.bak)
(But first backing it up to /etc/ppp/pap-secrets.bak)
Congratulations, it should be all set up!
Type '/sbin/ifup ppp0' to bring up your xDSL link and '/sbin/ifdown ppp0'
to bring it down.
Type '/sbin/pppoe-status /etc/sysconfig/network-scripts/ifcfg-ppp0'
to see the link status.

配置完成,

介紹三個命令:

pppoe-start 撥號

pppoe-stop 斷開

pppoe-status 查看撥號狀態

[root@localhost ~]# pppoe-start
[root@localhost ~]# pppoe-status
pppoe-status: Link is up and running on interface ppp0
4: ppp0: <pointopoint> mtu 1480 qdisc pfifo_fast state UNKNOWN qlen 3
link/ppp
inet xxx。xxx。xxx peer 1.1.1.1/32 scope global ppp0
valid_lft forever preferred_lft forever
/<pointopoint>
爬蟲第一步!就是搭建代理池!不然一封你IP!你還爬個錘子!

紅箭頭所指的位置是ip。

來測試一下是否可以連通網絡。

[root@localhost ~]# ping www.baidu.com
PING www.a.shifen.com (115.239.210.27) 56(84) bytes of data.
64 bytes from 115.239.210.27: icmp_seq=1 ttl=54 time=72.4 ms
64 bytes from 115.239.210.27: icmp_seq=2 ttl=54 time=70.4 ms
64 bytes from 115.239.210.27: icmp_seq=3 ttl=54 time=70.7 ms

ok,有網了。

代理選擇使用TinyProxy。

yum安裝:

[root@localhost ~]# yum -y install tinyproxy

Loaded plugins: fastestmirror

Loading mirror speeds from cached hostfile

* base: mirrors.163.com

* extras: mirrors.cn99.com

* updates: mirrors.163.com

No package tinyproxy available.

Error: Nothing to do

新系統上yum源需要自己配置,上面報錯是因為鏡像源沒有這個包。

添加 企業版 Linux 附加軟件包(EPEL),企業版 Linux 附加軟件包(以下簡稱 EPEL)是一個 Fedora 特別興趣小組,用以創建、維護以及管理針對企業版 Linux 的一個高質量附加軟件包集,面向的對象包括但不限於 紅帽企業版 Linux (RHEL) 、 CentOS、Scientific Linux (SL)、Oracle Linux (OL) 。( https://fedoraproject.org/wiki/EPEL/zh-cn )

centos系統安裝並啟用epel源:

yum install epel-release
[root@localhost ~]# yum install epel-release
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
* base: mirrors.163.com
* extras: mirrors.cn99.com
* updates: mirrors.163.com
Resolving Dependencies
--> Running transaction check
---> Package epel-release.noarch 0:7-11 will be installed
--> Finished Dependency Resolution
Dependencies Resolved
=================================================================================================================================================================================================================
Package Arch Version Repository Size
=================================================================================================================================================================================================================
Installing:
epel-release noarch 7-11 extras 15 k
Transaction Summary
=================================================================================================================================================================================================================
Install 1 Package
Total download size: 15 k
Installed size: 24 k
Is this ok [y/d/N]: y  #開始
Downloading packages:
epel-release-7-11.noarch.rpm | 15 kB 00:00:00
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
Installing : epel-release-7-11.noarch 1/1
Verifying : epel-release-7-11.noarch 1/1
Installed:
epel-release.noarch 0:7-11
Complete!  

重新執行thinproxy安裝命令:

爬蟲第一步!就是搭建代理池!不然一封你IP!你還爬個錘子!

配置代理,訪問源限制和端口設置。

[root@localhost ~]# vi /etc/tinyproxy/tinyproxy.conf

修改 Port 端口,默認為 8888

Port 8888

註釋掉 Allow,表示允許所有人訪問代理

#Allow 127.0.0.1

配置好了,啟動tinyproxy。

tinyproxy 啟動代理

killall tinyproxy 關閉所有端口(沒有killall命令,安裝yum install psmisc)

[root@localhost ~]# firewall-cmd --zone=public --add-port=8888/tcp --permanent #設置防火牆允許8888端口通過
success  
[root@localhost ~]# firewall-cmd --reload  #重載防火牆配置
success

全部配置完畢,測試代理是否可用。pppoe-status查看ip,谷歌插件SwitchyOmega配置代理。

爬蟲第一步!就是搭建代理池!不然一封你IP!你還爬個錘子!

爬蟲第一步!就是搭建代理池!不然一封你IP!你還爬個錘子!

選擇配置好的代理,能正常訪問表示代理服務器搭建成功。

Python操作pppoe更換ip

python3環境安裝

yum -y install wget  #安裝wget下載
wget https://www.python.org/ftp/python/3.6.5/Python-3.6.5.tgz #下載
tar -xvf Python-3.6.5.tgz  #解壓
cd Python-3.6.5  #進入文件夾
./configure prefix=/usr/local/python3  #配置編譯地址
make && make install  #開始編譯

ln -s /usr/local/python3/bin/python3 /usr/bin/python3  #配置軟連接
爬蟲第一步!就是搭建代理池!不然一封你IP!你還爬個錘子!

那順便把pip3和redis(python操作redis模塊)裝了,下一步會用到python3操作redis。

yum install -y python34-setuptools
easy_install-3.4 pip
pip3 install redis
爬蟲第一步!就是搭建代理池!不然一封你IP!你還爬個錘子!

import os
#切換IP,重啟代理服務
def changeIP():
os.system('pppoe-stop') #斷開
time.sleep(2)
os.popen('pppoe-start') #等待2s重撥
time.sleep(8)
os.popen('service tinyproxy restart') #等待重撥完畢,重啟代理服務
#取出當前IP
def extractIP():
infor = os.popen('pppoe-status').read() #讀取代理
ip = re.search('(\d+\.\d+\.\d+\.\d+)',infor).group(1) #正則匹配ip
print(ip)
return ip  

搭建代理池(redis)

下載安裝包

wget http://download.redis.io/releases/redis-4.0.2.tar.gz

解壓安裝包並安裝

tar xzf redis-4.0.2.tar.gz

cd redis-4.0.2

make

make install

啟動redis

redis-server

爬蟲第一步!就是搭建代理池!不然一封你IP!你還爬個錘子!

python操作redis寫入ip

import re,time,os,datetime,redis
#獲取時間
def getTime():
numtime = datetime.datetime.now().strftime('%Y-%m-%d %H-%M-%S---')
return numtime
#切換IP,重啟代理服務
def changeIP():
os.system('pppoe-stop')
time.sleep(2)
os.popen('pppoe-start')
time.sleep(8)
os.popen('service tinyproxy restart')
#取出當前IP
def extractIP():
infor = os.popen('pppoe-status').read()
try:
ip = re.search('(\d+\.\d+\.\d+\.\d+)',infor).group(1)
print(ip)
return ip
except Exception as e:
log_list.append(getTime()+'提取IP錯誤:'+str(e))
return False
#
#刪除ip 對應鍵ip1
def updateDel():
r = redis.Redis(host='', port=6379, db=0, decode_responses=True, password='')
r.delete('ip1')
#重新寫入ip 對應鍵ip1
def updatePut(ip):
print("更新ip")
r = redis.Redis(host='', port=6379, db=0, decode_responses=True, password='')
r.set('ip1',ip+':8888')
print("更新完畢")
if __name__ == '__main__':
#刪除ip後20s重撥
state = updateDel()
time.sleep(20)
os.popen('killall tinyproxy')
#重新連接
changeIP()
#取出當前IP

ip = extractIP()
if ip:
updatePut(ip)

redis用的鍵值對,也可以用表寫入,提取ip更方便。

爬蟲第一步!就是搭建代理池!不然一封你IP!你還爬個錘子!

這裡的意思是刪除數據庫中的ip後20s後重撥,保證已經提取出去的ip有20s的響應時間來跑爬蟲。

crontab設置定時任務

crontab -e

0 */1 * * * python3 /root/zhaozhi/IP.py & 1小時執行一次(測試好ip可用時間,自行更改)

多部署幾個代理服務器,保證切換ip的斷層會有ip可以提取


分享到:


相關文章: