Python中的代理IP池实现方法

2023-04-17 00:00:00 python 方法 代理

Python中实现代理IP池的步骤如下:

  1. 导入必要的库

使用Python实现代理IP池,需要导入requests、bs4和random库。其中,requests库用于发送http请求,bs4库用于解析html文档,random库用于随机选择代理IP。

import requests
from bs4 import BeautifulSoup
import random
  1. 获取代理IP

使用requests库发送get请求,获得代理IP网站的html文档,然后使用bs4库解析html文档,提取出其中所有代理IP信息。解析出来的代理IP信息保存在一个列表proxy_list中,每个元素都是一个字典,包含了代理IP和端口号。

url = "http://www.xicidaili.com/nn/"
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"}
html = requests.get(url, headers=headers)
soup = BeautifulSoup(html.content, 'html.parser')

proxy_list = []
for tr in soup.find_all('tr', class_=''):
    tds = tr.find_all('td')
    if len(tds) > 3:
        ip = tds[1].text.strip()
        port = tds[2].text.strip()
        protocol = tds[5].text.strip().lower()
        proxy_list.append({'ip': ip, 'port': port, 'protocol': protocol})
  1. 随机选择代理IP

从proxy_list中随机选择一个代理IP,并使用requests库的proxies参数将其添加到http请求中。如果请求失败(如超时或返回码不是200),则将该代理IP从列表proxy_list中删除,继续使用下一个代理IP。

while True:
    proxy_index = random.randint(0, len(proxy_list) - 1)
    proxy_ip = proxy_list[proxy_index]
    proxy = {proxy_ip['protocol']: proxy_ip['ip'] + ":" + proxy_ip['port']}
    try:
        response = requests.get("http://pidancode.com/", proxies=proxy, timeout=3)
        if response.status_code == 200:
            print(response.text)
            break
        else:
            proxy_list.remove(proxy_ip)
    except:
        proxy_list.remove(proxy_ip)

完整代码:

import requests
from bs4 import BeautifulSoup
import random

url = "http://www.xicidaili.com/nn/"
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"}
html = requests.get(url, headers=headers)
soup = BeautifulSoup(html.content, 'html.parser')

proxy_list = []
for tr in soup.find_all('tr', class_=''):
    tds = tr.find_all('td')
    if len(tds) > 3:
        ip = tds[1].text.strip()
        port = tds[2].text.strip()
        protocol = tds[5].text.strip().lower()
        proxy_list.append({'ip': ip, 'port': port, 'protocol': protocol})

while True:
    proxy_index = random.randint(0, len(proxy_list) - 1)
    proxy_ip = proxy_list[proxy_index]
    proxy = {proxy_ip['protocol']: proxy_ip['ip'] + ":" + proxy_ip['port']}
    try:
        response = requests.get("http://pidancode.com/", proxies=proxy, timeout=3)
        if response.status_code == 200:
            print(response.text)
            break
        else:
            proxy_list.remove(proxy_ip)
    except:
        proxy_list.remove(proxy_ip)

相关文章