Skip to content

HTTPX를 사용하여 다양한 プロキシ 구성을 구현합니다—인증 없는 プロキ시, 인증된 プロキ시, ローテーティングプロキシ, 그리고 폴백 プロキ시를 포함하여 다룹니다.

Notifications You must be signed in to change notification settings

bright-kr/httpx-with-proxy

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

7 Commits
 
 
 
 

Repository files navigation

HTTPX에서 프록시 사용하기

Promo

이 가이드는 인증 없는 프록시, 인증된 프록시, ローテーティング프록시, 그리고 フォールバック 프로キ시의 예시와 함께 HTTPX에서 프록시를 사용하는 방법을 설명합니다.

인증 없는 프록시 사용하기

인증 없는 プロキ시를 사용할 때는 사용자 이름이나 비밀번호를 사용하지 않으며, 모든 요청는 proxy_url로 전송됩니다. 아래는 인증 없는 プロ키시를 사용하는 코드 스니펫입니다:

import httpx

proxy_url = "http://localhost:8030"


with httpx.Client(proxy=proxy_url) as client:
    ip_info = client.get("https://geo.brdtest.com/mygeo.json")
    print(ip_info.text)

인증된 プロキ시 사용하기

인증된 プロ키시는 사용자 이름과 비밀번호가 필요합니다. 올바른 자격 증명을 제출하면 プロ키시에 대한 연결이 허용됩니다.

인증을 사용하는 경우 proxy_url은 다음과 같이 보입니다: http://<username>:<password>@<proxy_url>:<port_number>. 다음 예시는 zoneusername을 모두 사용하여 인증 문자열의 사용자 부분을 구성하는 방법을 보여줍니다. 또한 기본 연결로 Bright Data's datacenter proxies를 활용합니다.

import httpx

username = "your-username"
zone = "your-zone-name"
password = "your-password"

proxy_url = "http://brd-customer-{username}-zone-{zone}:{password}@brd.superproxy.io:33335"

ip_info = httpx.get("https://geo.brdtest.com/mygeo.json", proxy=proxy_url)

print(ip_info.text)

위 코드의 구성은 다음과 같습니다:

  • 먼저 설정 변수를 생성합니다: username, zone, password.
  • 이를 사용해 proxy_url을 생성합니다: "http://brd-customer-{username}-zone-{zone}:{password}@brd.superproxy.io:33335".
  • API로 요청를 전송하여 プロ키시 연결에 대한 일반 정보를 가져옵니다.

응답는 다음과 같이 표시되어야 합니다.

{"country":"US","asn":{"asnum":20473,"org_name":"AS-VULTR"},"geo":{"city":"","region":"","region_name":"","postal_code":"","latitude":37.751,"longitude":-97.822,"tz":"America/Chicago"}}

ローテーティングプロキ시 사용하기

ローテーティングプロキ시는 プロ키시 목록을 만들고 그중에서 무작위로 선택하는 것을 의미합니다. 아래 코드 스니펫은 countries 목록을 생성한 뒤, 각 요청마다 random.choice()를 사용해 목록에서 임의의 국가를 선택합니다. proxy_url은 해당 국가에 맞게 포맷팅됩니다. 코드에서 사용하는 rotating proxies 목록은 Bright Data의 것입니다.

import httpx
import asyncio
import random


countries = ["us", "gb", "au", "ca"]
username = "your-username"
proxy_url = "brd.superproxy.io:33335"

datacenter_zone = "your-zone"
datacenter_pass = "your-password"


for random_proxy in countries:
    print("----------connection info-------------")
    datacenter_proxy = f"http://brd-customer-{username}-zone-{datacenter_zone}-country-{random.choice(countries)}:{datacenter_pass}@{proxy_url}"

    ip_info = httpx.get("https://geo.brdtest.com/mygeo.json", proxy=datacenter_proxy)

    print(ip_info.text)

이 코드는 인증된 プロ키시 예시와 매우 유사합니다. 핵심 차이점은 다음과 같습니다:

  • 국가 배열을 생성합니다: ["us", "gb", "au", "ca"].
  • 단일 リクエ스트가 아니라 여러 リクエ스트를 수행합니다. 각 リクエ스트마다 proxy_url을 생성할 때 random.choice(countries)를 사용하여 매번 임의의 국가를 선택합니다.

フォールバック プロキ시 연결 생성하기

위의 모든 예시는 データセンタープロキ시와 무료 プロ키시를 사용합니다. 전자는 웹사이트에서 종종 차단되며, 후자는 신뢰성이 높지 않습니다. 이 모든 것이 제대로 작동하려면 レジデンシャルプロキ시로의 フォールバック가 있어야 합니다.

이를 위해 safe_get()이라는 함수를 만들겠습니다. 이를 호출하면 먼저 データセンタープロキ시 연결을 사용해 url을 가져오려고 시도합니다. 이 과정이 실패하면 레지덴셜 연결로 フォールバック 합니다.

import httpx
from bs4 import BeautifulSoup
import asyncio


country = "us"
username = "your-username"
proxy_url = "brd.superproxy.io:33335"

datacenter_zone = "datacenter_proxy1"
datacenter_pass = "datacenter-password"

residential_zone = "residential_proxy1"
residential_pass = "residential-password"

cert_path = "/home/path/to/brightdata_proxy_ca/New SSL certifcate - MUST BE USED WITH PORT 33335/BrightData SSL certificate (port 33335).crt"


datacenter_proxy = f"http://brd-customer-{username}-zone-{datacenter_zone}-country-{country}:{datacenter_pass}@{proxy_url}"

residential_proxy = f"http://brd-customer-{username}-zone-{residential_zone}-country-{country}:{residential_pass}@{proxy_url}"

async def safe_get(url: str):
    async with httpx.AsyncClient(proxy=datacenter_proxy) as client:
        print("trying with datacenter")
        response = await client.get(url)
        if response.status_code == 200:
            soup = BeautifulSoup(response.text, "html.parser")
            if not soup.select_one("form[action='/errors/validateCaptcha']"):
                print("response successful")
                return response
    print("response failed")
    async with httpx.AsyncClient(proxy=residential_proxy, verify=cert_path) as client:
        print("trying with residential")
        response = await client.get(url)
        print("response successful")
        return response

async def main():
    url = "https://www.amazon.com"
    response = await safe_get(url)
    with open("out.html", "w") as file:
        file.write(response.text)

asyncio.run(main())

코드 구성은 다음과 같습니다:

  • 이제 두 세트의 설정 변수가 있습니다. 하나는 データセンタープロキ시 연결용이고, 다른 하나는 レジデンシャルプロ키시 연결용입니다.
  • 이번에는 HTTPX의 더 고급 기능을 소개하기 위해 AsyncClient() 세션을 사용합니다.
  • 먼저 datacenter_proxy로 リクエ스트를 시도합니다.
  • 적절한 응답를 받지 못하면 residential_proxy를 사용하여 재시도합니다. 또한 코드의 verify 플래그에 유의하시기 바랍니다. Bright Data의 レジデンシャルプロ키시를 사용할 때는 SSL certificate를 다운로드하여 사용해야 합니다.
  • 정상적인 응답를 확보하면 페이지를 HTML 파일로 작성합니다. 브라우저에서 이 페이지를 열어 プロ키시가 실제로 접근한 내용과 우리에게 반환한 내용을 확인할 수 있습니다.

위 코드를 실행한 후 출력과 생성된 HTML 파일은 다음과 같이 표시되어야 합니다.

trying with datacenter
response failed
trying with residential
response successful

Screenshot of the Amazon homepage

결론

HTTPX를 Bright Data's top-tier proxy services와 결합하면 웹을 스크레이핑하기 위한 프라이빗하고 효율적이며 신뢰할 수 있는 방법을 얻을 수 있습니다. 지금 Bright Data의 プロ키시로 무료 체험을 시작해 보시기 바랍니다!

About

HTTPX를 사용하여 다양한 プロキシ 구성을 구현합니다—인증 없는 プロキ시, 인증된 プロキ시, ローテーティングプロキシ, 그리고 폴백 プロキ시를 포함하여 다룹니다.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published