간단한 암호화폐 가격 추적기 구축 가이드

댓글: 0

인기 있는 암호화폐의 가격 데이터를 추적하는 것은 높은 변동성으로 인해 어려울 수 있습니다. 암호화폐를 거래할 때는 철저한 조사를 수행하고 수익 기회를 활용할 수 있도록 준비하는 것이 필수적입니다. 정확한 가격 데이터를 얻는 것은 때때로 어려울 수 있습니다. 이러한 목적으로 API가 일반적으로 사용되지만 무료 구독에는 종종 제한이 따릅니다.

여기서는 파이썬을 사용해 상위 150개 암호화폐의 현재 가격을 주기적으로 스크래핑하는 방법을 살펴보겠습니다. 암호화폐 가격 추적기는 다음과 같은 데이터를 수집합니다:

  • 코인 이름;
  • 티커;
  • 가격;
  • 24시간 가격 변동률.

1단계: 라이브러리 가져오기

Python 스크립트의 첫 번째 단계는 필요한 라이브러리를 가져오는 것입니다. 각각 요청을 전송하고 HTML 파일에서 데이터를 추출하기 위해 `requests`와 `BeautifulSoup` 라이브러리를 사용합니다.

import requests
from bs4 import BeautifulSoup
import csv
import time
import random

또한 CSV 파일 작업에는 `csv`를, 가격 업데이트 주기와 프록시 로테이션 제어에는 각각 `time`과 `random`을 사용할 것입니다.

2단계: 프록시 설정

프리미엄 프록시 없이 요청을 보낼 때 '액세스 거부' 응답이 나타날 수 있습니다.

이 방법으로 프록시를 설정할 수 있습니다:

proxy = {
 "http": "http://Your_proxy_IP_Address:Your_proxy_port",
}
html = requests.get(url, proxies=proxy)

인증된 프록시의 경우 다음 형식을 사용합니다:

proxy = {
 "http": "http://username:password@Your_proxy_IP_Address:Your_proxy_port",
}
html = requests.get(url, proxies=proxy)

"Your_proxy_IP_Address"와 "Your_proxy_port"를 실제 프록시 주소로 바꿔야 합니다. 또한 "username" 및 "password"의 값은 자격 증명으로 바꾸세요.

3단계: 프록시 교체

프록시 로테이션은 최신 웹사이트가 동일한 IP 주소에서 여러 요청을 감지하면 봇과 스크레이퍼에 대한 액세스를 차단하거나 제한하는 경우가 많으므로 성공적인 스크래핑을 위해 매우 중요한 기술입니다. 프록시 로테이션을 설정하려면 무작위 라이브러리를 가져옵니다.

로테이션할 프록시 목록을 만듭니다:

# 프록시 목록
proxies = [ 
 "username:password@Your_proxy_IP_Address:Your_proxy_port1",
 "username:password@Your_proxy_IP_Address:Your_proxy_port2",
 "username:password@Your_proxy_IP_Address:Your_proxy_port3",
 "username:password@Your_proxy_IP_Address:Your_proxy_port4",
 "username:password@Your_proxy_IP_Address:Your_proxy_port5",
]

다음으로 각 요청에 대해 목록에서 프록시를 무작위로 선택하는 get_proxy() 함수를 정의합니다.

# 메서드를 사용하여 프록시를 회전합니다.
def get_proxy(): 
  # 목록에서 임의의 프록시를 선택합니다.
  proxy = random.choice(proxies) 
  return {
            "http": f'http://{proxy}',
            "https": f'http://{proxy}'
    }

이 함수는 HTTP 프로토콜에 대해 선택한 프록시가 포함된 사전을 반환합니다. 이 설정을 사용하면 스크래핑하는 웹사이트에 다수의 오가닉 사용자로 표시되어 스크래핑 방지 조치를 우회할 가능성이 높아집니다.

4단계: 암호화 데이터 가져오기 및 구문 분석

get_crypto_prices() 함수는 Coindesk에서 암호화폐 가격을 스크랩합니다. 이 함수는 요청.get() 함수를 사용하여 웹사이트에 GET 요청을 보내며, 인자로 로테이팅 프록시를 전달합니다. 응답의 텍스트와 파서 "html.parser"를 BeautifulSoup 생성자에 전달합니다.

def get_crypto_prices():
    url = "https://crypto.com/price"
    html = requests.get(url, proxies=get_proxy())
    soup = BeautifulSoup(html.text, "html.parser")

5단계: 사이트 구조 이해

데이터 추출을 시작하기 전에 사이트 구조를 이해해야 합니다. 브라우저의 개발자 도구를 사용하여 웹페이지의 HTML을 검사할 수 있습니다. 개발자 도구에 액세스하려면 웹페이지를 마우스 오른쪽 버튼으로 클릭하고 "검사"를 선택하면 됩니다.

1.png

그런 다음 BeautifulSoup의 find_all() 함수와 CSS 선택기 'tr', class_='css-1cxc880'을 사용하여 페이지의 모든 가격 컨테이너를 찾고 각 컨테이너의 코인 이름, 시세, 가격, 24시간 변동률을 추출합니다. 이 데이터는 사전에 저장된 다음 가격 목록에 추가됩니다.

2.png

코인 이름 추출하기

여기서는 row.find('p', class_='css-rkws3')를 사용하여 클래스가 "css-rkws3"인 'p' 요소를 찾습니다. 그런 다음 텍스트를 추출하여 'name' 변수에 저장합니다.

3.png

coin_name_tag = row.find('p', class_='css-rkws3')
name = coin_name_tag.get_text() if coin_name_tag else "no name entry"

티커 추출하기

마찬가지로 row.find("span", class_="css-1jj7b1a")를 사용하여 "css-1jj7b1a" 클래스를 가진 스팬 요소를 찾습니다. get_text() 메서드는 텍스트 콘텐츠를 추출하여 티커를 제공합니다.

4.png

coin_ticker_tag = row.find('span', class_='css-1jj7b1a')
ticker = coin_ticker_tag.get_text() if coin_ticker_tag else "no ticker entry"

가격 추출하기

"css-b1ilzc" 클래스를 가진 "div" 요소를 찾습니다. 그런 다음 텍스트 콘텐츠를 제거하여 가격 변수에 할당합니다. 조건문을 사용하여 요소가 존재하지 않을 수 있는 경우를 처리합니다.

5.png

coin_price_tag = row.find('div', class_='css-b1ilzc')
price = coin_price_tag.text.strip() if coin_price_tag else "no price entry"

변동 비율 추출하기

마찬가지로 "css-yyku61" 클래스를 가진 "p" 요소를 찾아 백분율 변화를 추출합니다. 텍스트 콘텐츠는 제거되고 조건문은 잠재적인 부재를 처리합니다.

6.png

coin_percentage_tag = row.find('p', class_='css-yyku61')
percentage = coin_percentage_tag.text.strip() if coin_percentage_tag else "no percentage entry"

이 모든 것을 종합하면 다음과 같은 for 루프가 생깁니다:

for row in price_rows:
        coin_name_tag = row.find('p', class_='css-rkws3')
        name = coin_name_tag.get_text() if coin_name_tag else "no name entry"

        coin_ticker_tag = row.find('span', class_='css-1jj7b1a')
        ticker = coin_ticker_tag.get_text() if coin_ticker_tag else "no ticker entry"
        
        coin_price_tag = row.find('div', class_='css-b1ilzc')
        price = coin_price_tag.text.strip() if coin_price_tag else "no price entry"

        coin_percentage_tag = row.find('p', class_='css-yyku61')
        percentage = coin_percentage_tag.text.strip() if coin_percentage_tag else "no percentage entry"
        
        prices.append({
            "Coin": name,
            "Ticker": ticker,
            "Price": price,
            "24hr-Percentage": percentage
        })
    
    return prices

6단계: 데이터를 CSV로 내보내기

export_to_csv() 함수는 스크랩된 데이터를 CSV 파일로 내보내기 위해 정의되었습니다. CSV 라이브러리를 사용하여 가격 목록의 데이터를 지정된 CSV 파일에 씁니다.

 def export_to_csv(prices, filename="proxy_crypto_prices.csv"):
       with open(filename, "w", newline="") as file:
           fieldnames = ["Coin", "Ticker", "Price", "24hr-Percentage"]
           writer = csv.DictWriter(file, fieldnames=fieldnames)
           writer.writeheader()
           writer.writerows(prices)

7단계: 트래커 실행

스크립트의 주요 부분에서는 get_crypto_prices() 함수를 호출하여 가격을 스크래핑하고 export_to_csv() 함수를 호출하여 가격을 CSV 파일로 내보냅니다. 그런 다음 가격을 다시 업데이트하기 전에 5분(300) 동안 기다립니다. 이 작업은 무한 루프에서 수행되므로 프로그램이 중지될 때까지 가격이 5분마다 계속 업데이트됩니다.

if __name__ == "__main__":
       while True:
           prices = get_crypto_prices()
           export_to_csv(prices)
           print("Prices updated. Waiting for the next update...")
           time.sleep(300)  # 5분마다 가격 업데이트

전체 코드

다음은 이 프로젝트에서 다룬 모든 기술과 단계를 통합하여 암호화폐 가격 추적기를 구축하는 간소화된 접근 방식을 제공하는 전체 코드입니다.

import requests
from bs4 import BeautifulSoup
import csv
import time
import random

# 프록시 목록
proxies = [
     "username:password@Your_proxy_IP_Address:Your_proxy_port1",
     "username:password@Your_proxy_IP_Address:Your_proxy_port2",
     "username:password@Your_proxy_IP_Address:Your_proxy_port3",
     "username:password@Your_proxy_IP_Address:Your_proxy_port4",
     "username:password@Your_proxy_IP_Address:Your_proxy_port5",
]

# 프록시를 회전하는 사용자 지정 방법
def get_proxy():
    # 목록에서 임의의 프록시를 선택합니다.
    proxy = random.choice(proxies)
    # http 프로토콜 프록시가 포함된 사전을 반환합니다.
    return {"http": f'http://{proxy}',
            "https": f'http://{proxy}'
          }


def get_crypto_prices():
    url = "https://crypto.com/price"
    html = requests.get(url, proxies=get_proxy())
    print(html.status_code)
    soup = BeautifulSoup(html.content, "html.parser")

    price_rows = soup.find_all('tr', class_='css-1cxc880')

    prices = []
    for row in price_rows:
        coin_name_tag = row.find('p', class_='css-rkws3')
        name = coin_name_tag.get_text() if coin_name_tag else "no name entry"

        coin_ticker_tag = row.find('span', class_='css-1jj7b1a')
        ticker = coin_ticker_tag.get_text() if coin_ticker_tag else "no ticker entry"
        
        coin_price_tag = row.find('div', class_='css-b1ilzc')
        price = coin_price_tag.text.strip() if coin_price_tag else "no price entry"

        coin_percentage_tag = row.find('p', class_='css-yyku61')
        percentage = coin_percentage_tag.text.strip() if coin_percentage_tag else "no percentage entry"
        
        prices.append({
            "Coin": name,
            "Ticker": ticker,
            "Price": price,
            "24hr-Percentage": percentage
        })
    
    return prices



def export_to_csv(prices, filename="proxy_crypto_prices.csv"):
    with open(filename, "w", newline="") as file:
        fieldnames = ["Coin", "Ticker", "Price", "24hr-Percentage"]
        writer = csv.DictWriter(file, fieldnames=fieldnames)

        writer.writeheader()
        writer.writerows(prices)


if __name__ == "__main__":
    while True:
        prices = get_crypto_prices()
        export_to_csv(prices)
        print("Prices updated. Waiting for the next update...")
        time.sleep(300)  # 5분마다 가격 업데이트(필요에 따라 조정)

결과

암호화폐 가격 추적기의 결과는 아래와 같이 "proxy_crypto_prices.csv"라는 CSV 파일에 저장됩니다:

7.jpg

파이썬의 간단한 구문은 자동화된 암호화폐 가격 추적기를 구축하는 데 이상적인 선택입니다. 이 프로그래밍 언어는 새로운 기능을 추가하고 트래커의 기능을 확장하는 데 용이합니다. 제공된 예제에서는 지정된 간격으로 암호화폐 시세를 자동으로 업데이트하고, 프록시를 통해 데이터를 수집하고, 사용자 친화적인 형식으로 저장할 수 있는 기본 스크레이퍼를 만드는 방법을 보여드립니다.

댓글:

0 댓글