前言
- 首先說一下代理IP的用法途(代碼中會有涉及):代理IP可以用來隱藏你的真實IP,你訪問網站是通過代理服務器來做一箇中轉,所以目標服務器只能看到代理服務器的IP地址,這樣就可以讓你的IP地址實現隱身的功能
準備工作
- 我這邊是找到了一個平臺:https://www.kuaidaili.com/,先在地址後面加robots.txt查看平臺的robots協議(https://www.kuaidaili.com/robots.txt)如下,可以看到平臺未明令禁止爬蟲爬取的頁面,那我們就可以放心爬了。
- 按f12分析一下頁面先,左上角箭頭選中ip之後直接右鍵複製XPath。
- 測試後發現,IP不是通過接口傳輸的,而是存在在靜態頁面上,這就省事很多了。
- 並且,點擊下一頁後,url變化很小。
- url很簡單,這裏就不過多分析了,直接上代碼。
上代碼
- 首先爬取前五頁。(這裏要注意加上headers模擬瀏覽器訪問)
#爬取數據
def get_ip():
for page in range(1,5):
print("=============================正在抓取第{}頁數據==============".format(page))
base_url = 'https://www.kuaidaili.com/free/inha/{}/'.format(page)
headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:75.0) Gecko/20100101 Firefox/75.0'}
response = requests.get(base_url,headers=headers)
data = response.text
#print(data)
html_data = parsel.Selector(data)
# 解析數據
parsel_list = html_data.xpath('//table[@class="table table-bordered table-striped"]/tbody/tr')
for tr in parsel_list:
proxies_dict = {}
http_type = tr.xpath('./td[4]/text()').extract_first() #用xpath找到目標
ip_num = tr.xpath('./td[1]/text()').extract_first()
ip_port = tr.xpath('./td[2]/text()').extract_first()
proxies_dict[http_type] = ip_num + ':' + ip_port #將ip地址和端口號用":"連接
proxies_list.append(proxies_dict)
print(proxies_dict)
time.sleep(0.5)
print(proxies_list)
print("獲取到的代理ip數量:",len(proxies_list))
return proxies_list
- 然後,考慮到有些ip能用,有些ip不能用,所以需要對其進行清洗。剔除不能用的或反應慢的。這裏可以試着用代理ip訪問一下百度首頁,並檢測返回狀態來確定ip是否可用。
def check_ip(proxies_list):
"""檢測代理ip的質量"""
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:75.0) Gecko/20100101 Firefox/75.0'}
can_use = []
for proxy in proxies_list:
try:
response = requests.get('https://www.baidu.com',headers=headers,proxies=proxy,timeout=0.08) #代理ip使用方式,如果要篩選更快的ip,timeout可適當降低
if response.status_code == 200: #返回狀態碼爲200即爲可用
can_use.append(proxy)
except Exception as e:
print(e)
return can_use
- 簡單組合一下,爬取部分就算搞完了。
ip_list = get_ip() #獲取IP
can_use = can_use(ip_list) #清洗IP
代理IP使用
- 這是我當時腦門一熱想到的通過用代理ip進入直播間來增加人氣,實驗後發現,我太天真了,實驗失敗,根本不能增加人氣,各位可以傳入別的網址來實現用代理IP訪問固定網站,can_use參數就傳入上面得到的can_use就行。
def start(url,can_use):
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:75.0) Gecko/20100101 Firefox/75.0'}
for proxy in can_use:
try:
response = requests.get(url,headers=headers,proxies=proxy,timeout=1)
if response.status_code == 200:
print("進入直播間。。。")
except Exception as e:
print(e)
- 其次,我覺得如果用代理IP爬取網站內容的話,可能會繞過網站的反爬策略,只是思考了一下,並未實踐。
- 或者也可以將代理IP寫入數據庫,留着慢慢用。
# 入庫
def engine_in(ip_list):
conn = pymysql.connect(host='localhost',user='root',password='123',database='size',port=3306) #連接數據庫
cursor = conn.cursor()
for ip in ip_list:
sql = "INSERT INTO ip(ip) values('" + ip + "');" #SQL語句
cursor.execute(sql) #執行SQL語句
conn.commit()
conn.close()
後記
- Tip:寫爬蟲前首先要看一下該網站的robots.txt協議是否允許爬取,在其允許範圍內適當爬取數據。
爬取代理ip的想法是我從某學習平臺學到的,若有冒犯,請聯繫刪除