Python實現IP代理的方法
數碼 2
本文將介紹如何使用Python代理IP。在網絡爬蟲、反爬蟲和自動化測試中,IP代理是必考慮的因素之一。使用代理IP可以有效地提高爬取數據的成功率,增強爬取效率,維護爬蟲的匿名性。Python提供了許多第三方庫和框架,可以方便地實現IP代理。
使用Python實現IP代理需要安裝requests和bs4庫。在終端輸入以下命令安裝:
pip install requests
pip install beautifulsoup4
獲取代理IP有兩種方式:手動獲取和自動獲取。手動獲取需要從免費代理IP網站上複製粘貼IP,速度較慢,但可以減少自動獲取的誤差。自動獲取需要使用第三方庫或者API,速度更快,但可能會存在ip不可用或者被封禁的情況
通過免費代理網站手動獲取IP,如”西刺免費代理IP”、”快代理”等。將IP和對應端口號複製到代碼中。
proxies = {
"http": "http://101.132.122.230:80",
"https": "http://101.236.20.23:8866"
}
使用第三方庫或者API獲取免費代理IP。這裡我們使用”requests”和”beautifulsoup4″庫,爬取代理IP池網站的數據,然後篩選出可用的IP。
import requests
from bs4 import BeautifulSoup
def get_ip():
url = "http://www.xicidaili.com/nn/"
headers = {'User-Agent': 'Mozilla/5.0'}
html = requests.get(url=url, headers=headers).text
soup = BeautifulSoup(html, 'html.parser').find_all('tr', class_='odd')
ips = []
for i in soup:
soup_td = i.find_all('td')
ip = soup_td[1].text + ':' + soup_td[2].text
ips.append(ip)
print("獲取代理IP成功")
return ips
def check_ip(ips):
usable_ips = []
url = "https://www.baidu.com/"
headers = {'User-Agent': 'Mozilla/5.0'}
for ip in ips:
try:
proxy = {'http': 'http://' + ip, 'https': 'https://' + ip}
response = requests.get(url=url, headers=headers, proxies=proxy, timeout=1)
if response.status_code == 200:
usable_ips.append(ip)
except:
continue
print("篩選代理IP成功")
return usable_ips
ips = get_ip()
usable_ips = check_ip(ips)
proxies = {'http': 'http://' + usable_ips[0], 'https': 'https://' + usable_ips[0]}
將獲取到的代理IP設置在請求頭部中即可。
import requests
url = "https://www.baidu.com/"
headers = {'User-Agent': 'Mozilla/5.0'}
proxies = {
"http": "http://101.132.122.230:80",
"https": "http://101.236.20.23:8866"
}
response = requests.get(url=url, headers=headers, proxies=proxies)
print(response.text)
高匿名代理IP指請求頭部中不包含代理IP的相關信息,提高匿名性。在獲取IP時,需篩選出高匿代理。以下是一個簡單的例子:
def check_high_ip(ips):
high_ips = []
url = "https://httpbin.org/get"
headers = {'User-Agent': 'Mozilla/5.0'}
for ip in ips:
try:
proxy = {'http': 'http://' + ip, 'https': 'https://' + ip}
response = requests.get(url=url, headers=headers, proxies=proxy, timeout=1)
if response.status_code == 200:
if ip not in response.text:
continue
else:
high_ips.append(ip)
except:
continue
print("篩選高匿代理IP成功")
return high_ips
為了防止封禁或者被限制,需要動態切換代理IP。我們可以設置一個閾值,當訪問次數達到閾值時,重新獲取代理IP。
import requests
proxies = [{'http': 'http://' + usable_ips[i], 'https': 'https://' + usable_ips[i]} for i in range(len(usable_ips))]
url = "https://www.baidu.com/"
headers = {'User-Agent': 'Mozilla/5.0'}
count = 0
threshold = 10
for proxy in proxies:
if count > threshold:
ips = get_ip()
usable_ips = check_ip(ips)
proxies = [{'http': 'http://' + usable_ips[i], 'https': 'https://' + usable_ips[i]} for i in range(len(usable_ips))]
print("獲取新代理IP成功")
count = 0
try:
response = requests.get(url=url, headers=headers, proxies=proxy, timeout=1)
print(response.text)
count += 1
except:
continue
本文介紹了兩種獲取代理IP的方法,手動獲取和自動獲取,同時實現了高匿名代理IP和動態切換代理IP的功能,使爬蟲的效率更高,匿名性更好。