webpagetest api 를 사용하여 여러 웹사이트들을 1회씩 지역을 변경하여 속도 자동화 테스트 파이썬으로 작성

 

import requests
import json
import time
import csv

url = 'https://www.google.com'
locations = [
    'ec2-us-east-1:Chrome.Native',
    'gce-us-west3:Chrome.Native',
    'ec2-us-west-1:Chrome.Native',
    'ec2-ca-central-1:Chrome.Native',
    # 다른 지역도 추가
]
private = 1
video = 1
request_id = 'json'
tcpdump = 1
pngss = 1
timeline = 1

# CSV 파일로 저장할 데이터 리스트 초기화
csv_data = [['Location', 'From', 'Fully Loaded (ms)']]

for location in locations:
    api_url = f"https://www.webpagetest.org/runtest.php?url={url}&location={location}&private={private}&video={video}&requestId={request_id}&tcpdump={tcpdump}&pngss={pngss}&timeline={timeline}"

    # API 호출
    response = requests.get(api_url)

    # 결과 확인
    result = response.json()
    if result['statusCode'] == 200:
        test_id = result['data']['testId']
        print(f"Test submitted successfully for location {location}. Test ID: {test_id}")

        # 테스트 상태 확인을 위한 URL
        test_status_url = f"https://www.webpagetest.org/testStatus.php?test={test_id}"

        # 테스트 결과를 가져올 URL
        json_result_url = f"https://www.webpagetest.org/jsonResult.php?test={test_id}"

        # 테스트 상태 확인
        while True:
            status_response = requests.get(test_status_url)
            status_data = status_response.json()

            if status_data['statusText'] == 'Test Complete':
                # 테스트가 완료된 경우 결과를 가져옴
                result_response = requests.get(json_result_url)
                result_data = result_response.json()

                # CSV 데이터에 추가
                csv_data.append([result_data['location'], result_data['from'], result_data['average']['firstView']['fullyLoaded']])
                break
            else:
                print(f"Test is not yet complete for location {location}. Status: {status_data['statusText']}")
                time.sleep(60)  # 1분 대기
    else:
        print(f"Error submitting test for location {location}. Status code: {result['statusCode']}")

# CSV 파일로 저장
csv_file_name = 'test_results.csv'
with open(csv_file_name, 'w', newline='') as csv_file:
    writer = csv.writer(csv_file)
    writer.writerows(csv_data)

print(f"All tests completed successfully. Results saved to {csv_file_name}")

 

pro 버전 추가 가능 location

Atlanta - US
Boston - US
Chicago - US
Dallas - US
Miami - US
New York City - US
Los Angeles - US
Seattle - US
Portland -US

"이 포스팅은 쿠팡 파트너스 활동의 일환으로, 이에 따른 일정액의 수수료를 제공받습니다."
Posted by 프리스케이터