爬蟲 代理IP
阿新 • • 發佈:2018-11-01
爬蟲 獲取代理IP
之前說過,因為某些原因,IP被封了,所以回過頭排查了一下關於代理IP的問題。
代理IP的作用
代理IP
簡單的來說,就是代替你訪問網站的IP,每臺電腦都有自己的IP,在從事爬蟲的時候,如果你直接使用自己的IP,被爬的網站檢測到,會很快的封掉你的IP,從事違法工作的,甚至定位到你的位置。那麼我們在使用爬蟲的時候,怎麼能不使用自己的IP呢,那麼就用代理的IP。
這裡用的代理IP是從西刺的網站上爬下來的,西刺提供的代理IP為高可匿的,但是並不是所有的都有效,有效的太少了,需要我們去檢驗篩選出可用的IP,再去為吾所用。
代理IP的獲取
import requests
from bs4 import BeautifulSoup
headers = {
'Host': 'www.xicidaili.com',
'User-Agent': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)',
'Accept': r'application/json, text/javascript, */*; q=0.01',
'Referer': r'http://www.xicidaili.com/',
}
#此處只爬取了第一頁的
html = requests.get(r'http://www.xicidaili.com/nn/' , headers=headers)
#用到BeautifulSoup進行解析
soup = BeautifulSoup(html.text, features="html.parser")
all_tr = soup.find_all("tr", class_="odd")
#得到所有的帶標籤的IP
ip_list = []
for i in range(1, len(all_tr)):
#對IP進行解析
ip = all_tr[i].contents[3].string+":"+all_tr[i].contents[5].string
ip_list.append(ip)
#列印第一頁獲取到的IP數量
print(len(ip_list))
代理IP的檢驗
#將有效的IP存到檔案中,檔名位ip.txt
f = open("ip.txt", "w")
#記錄有效個數
sum = 0
#記錄到第幾個了
i = 0
for proxy in all_id:
i += 1
print(i)
try:
#設定timeout=10,超過10就不訪問了,太浪費時間
#http://icanhazip.com/網站的作用是返回訪問此網站的IP地址
res = requests.get('http://icanhazip.com/', proxies={"http":"http://"+proxy}, timeout=10)
#返回訪問此網站的IP地址
print(res.content)
#訪問成功狀態碼為200
if( res.status_code == 200 ):
#存入
f.write(proxy+'\n')
sum += 1
except :
print ("connect failed")
#關閉
f.close()
代理IP的使用
#118.190.95.43:9001為爬來的代理IP,使用就可以了
html = requests.get(url, headers=headers, proxies={"http" : "http://118.190.95.43:9001"})
總的程式碼
# coding=utf-8
from urllib import request
import requests
from bs4 import BeautifulSoup
#爬取
def get_ip():
headers = {
'Host': 'www.xicidaili.com',
'User-Agent': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)',
'Accept': r'application/json, text/javascript, */*; q=0.01',
'Referer': r'http://www.xicidaili.com/',
}
# req = request.Request(r'http://www.xicidaili.com/nn/', headers=headers)
# response = request.urlopen(req)
# html = response.read().decode('utf-8')
#requests.get訪問不了,用上邊三句代替這一句
html = requests.get(r'http://www.xicidaili.com/nn/', headers=headers)
soup = BeautifulSoup(html.text, features="html.parser")
all_tr = soup.find_all("tr", class_="odd")
ip_list = []
for i in range(1, len(all_tr)):
ip = all_tr[i].contents[3].string+":"+all_tr[i].contents[5].string
ip_list.append(ip)
print(len(ip_list))
return ip_list
#驗證
def get_best_ip(all_id):
f = open("ip.txt", "w")
sum = 0
i = 0
for proxy in all_id:
i += 1
print(i)
try:
res = requests.get('http://icanhazip.com/', proxies={"http":"http://"+proxy}, timeout=10)
print(res.content)
if( res.status_code == 200 ):
f.write(proxy+'\n')
sum += 1
except :
print ("connect failed")
f.close()
return sum
if __name__ == "__main__":
all_id = get_ip()
sum = get_best_ip(all_id)
print("成功獲取", sum, "個可用代理ip")