代理ip 多執行緒 python寫法

__username發表於2024-11-23

先封裝

import requests



def get_proxy():

    url = "http://api1.xxxxxxxxxx0&format=txt"
    response = requests.get(url)
    print(response.status_code)
    print(response.text)

    ip = response.text

    return ip



if __name__ == '__main__':
    get_proxy()

例子

import schedule
import threading
import time
from loguru import logger
import requests
import sys
from fake_useragent import UserAgent
from get_proxy import get_proxy


ua = UserAgent()
print(ua.random)

logger.add("debug1.log", format="{time:YYYY-MM-DD at HH:mm:ss} | {message}", level="DEBUG")

cookies = {
    'xxxx': 'xxxx',
}

headers = {
    'User-Agent': ua.random,
    'Content-Type': 'application/json',
    'Origin': 'https://evt.tomorrow365.com',
    'ax': 'xxxxx',
    'xweb_xhr': '1',
    'X-APP-APPID': '3',
    'App-Client-Id': '6',
    'Sec-Fetch-Site': 'cross-site',
    'Sec-Fetch-Mode': 'cors',
    'Sec-Fetch-Dest': 'empty',
    'Referer': 'https://xxxxx',
    'Accept-Language': 'zh-CN,zh;q=0.9',
    # 'Cookie': 'xxxxx',
}

json_data = '{"productId":"xxxxx","productQuantity":"xxxx","productSkuId":"xxxx","peopleInfoReq":[],"deductionAmount":0,"payAmount":xxx}'

# 建立一個全域性事件物件,用於線上程間通訊
stop_event = threading.Event()







def post_ticket():
    try:
        ip = get_proxy().strip()
        proxy = {
            'http': 'http://' + ip,
            'https': 'http://' + ip
        }
        print(f'使用得代理:{proxy}')
        response = requests.post(
            'https://xxxxxxxxxx/generateOrder',
            proxies=proxy,
            cookies=cookies,
            headers=headers,
            data=json_data,
        )

        logger.info(response.text)

        # 檢查響應內容,如果成功則設定事件,停止所有執行緒
        if any(keyword in str(response.text) for keyword in ['成功', 'xxxxx']):
            logger.info("成功,停止所有執行緒。")
            stop_event.set()  # 設定事件,通知其他執行緒停止
            return True  # 返回成功狀態
    except Exception as e:
        logger.error(e)
    return False  # 返回失敗狀態

def task():
    time.sleep(0.6)
    threads = []
    for i in range(10):  # 建立 10 個執行緒
        t = threading.Thread(target=post_ticket_multiple)
        threads.append(t)
        t.start()

    # 等待所有執行緒完成
    for t in threads:
        t.join()

def post_ticket_multiple():
    for _ in range(20):  # 每個執行緒傳送 50 個請求
        if stop_event.is_set():  # 檢查是否需要停止執行緒
            logger.info("檢測到停止訊號,執行緒終止。")
            break
        if post_ticket():  # 如果成功,停止當前執行緒
            break
        time.sleep(0.1)

logger.info('test one...')
post_ticket()
logger.info('test wait...')

# 安排任務在 12:59:59 執行
schedule.every().day.at("15:03:59").do(task)

while True:
    schedule.run_pending()
    time.sleep(1)  # 避免 CPU 佔用過高

相關文章