Profile picture

[Python] 무료 프록시 서버 사용하기

JaehyoJJAng2023년 05월 26일

▶︎ proxy-requests


a. proxy-requests 라이브러리 설치

$ pip install proxy-requests

b. 간단하게 프록시 서버 사용하기

from proxy_requests import ProxyRequests

url : str = 'https://api.ipify.org'
r = ProxyRequests(url)
r.get()

▶︎ 무료 프록시 서버

라이브러리를 사용하지 않고 무료 프록시 서버 리스트를 제공하는 사이트의 웹 구조를 분석해서 해당 서버 정보와 포트 정보를 저장하여 프록시로 활용하는 방법이 존재한다

이를 위해서는 HTML을 구조적으로 해석이 가능한 라이브러리가 필요한데 여기선 beautifulsoup를 사용하여 HTML을 파싱해 프록시 서버의 IP와 PORT를 가져와 볼 것이다.

그리고 requests 라이브러리를 사용하여 HTTP 요청을 보낼 때 추출한 프록시 서버의 정보를 프록시로 설정하면 끝이다.

예제를 살펴보며 확인해보자.


a. 라이브러리 설치

$ pip install requests bs4

b. 코드를 작성해보자.
{% include codeHeader.html name="main.py" %}

from bs4 import BeautifulSoup as bs
import requests as rq

def get_soup_object(response: rq.Response) -> bs:
    return bs(response.text,'html.parser')

def get_proxies(url: str) -> list[str]:
    proxies_list: list[str] = []

    resp: rq.Response = rq.get(url=url,verify=False)
    soup: bs = get_soup_object(response=resp)
    proxies_length : int = len(soup.select('table.table.table-striped.table-bordered > tbody > tr'))
    
    for index in range(proxies_length):            
        proxies: list = soup.select('table.table.table-striped.table-bordered > tbody > tr')

        # Code (한국: KR만 가져옴)
        code: str = proxies[index].select('td')[2].text.strip()
        if code == 'KR':
            # Port
            port: str = proxies[index].select('td')[1].text.strip()

            # IP
            ip: str = proxies[index].select('td')[0].text.strip()

            # Proxy set
            proxy : str = f'{ip}:{port}'
            proxies_list.append(proxy)
    return proxies_list

def main() -> None:
    # Proxy list URL
    free_proxy_server_url: str = 'https://free-proxy-list.net'

    # Get Proxies 
    proxies: list[str] = get_proxies(url=free_proxy_server_url)
    
    url = 'https://httpbin.org/ip'
    for proxy in proxies:
        print(f'Request {proxy} ...')
        
        # Set proxies
        proxies: dict[str,str] = {'http': proxy,'https': proxy}
        
        # Proxy Testing ...
        try:
            response : rq.Response = rq.get(url=url,proxies=proxies,timeout=10)
            if response.status_code == 200:
                print(f'Proxy {proxy} is working.')
                print(f'Your IP: {response.json()["origin"]}\n')
        except rq.exceptions.RequestException as e:
            print(f'Proxy {proxy} is not working\n')
            continue
    
if __name__ == '__main__':
    main()

‣ 코드 설명

함수명 설명
get_soup_object() 모듈의 응답을 받아서 HTML 문서를 파싱하여 BeautifulSoup 객체 반환
get_proxies() - 주어진 URL에서 프록시 목록 가져오는 함수
- 먼저 주어진 URL로 GET 요청을 보내고, 응답을 받아 bs 객체로 파싱
- 프록시 목록은 HTML 테이블에서 td 태그를 선택하여 추출
- 각 프록시에 대해 IP 주소, 포트 번호, 국가(=KR)를 추출하고 이를 프록시 목록 리스트 변수에 추가하였음
proxies=proxies 추출한 프록시 서버 정보를 가지고 프록시 요청 보냄

‣ 실행 결과

$ python3 main.py

image


Loading script...