吾爱破解 - LCG - LSG |安卓破解|病毒分析|www.52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 1280|回复: 28
收起左侧

[求助] python代码,改成运行9次暂停50秒一直循环

[复制链接]
sun4ay 发表于 2023-7-26 06:26
25吾爱币
这个代码写的刷票软件,想改成定时运行9次后暂停50秒一直循环下去
[Python] 纯文本查看 复制代码
# -*- coding: utf-8 -*-
 
import time
from datetime import datetime
from datetime import timedelta
from datetime import timezone
import grequests
from fake_useragent import UserAgent
 
url = 'https://www.baidu.com'
ua = UserAgent()
headers = {
    'Tyauthtoken': '4FE86EA2C64241BCA0220AFB0C517C2F',
    "User-Agent": ua.random
}
 
json = {
    # 1231231
    # 123123
}
 
 
def execute_command(num=1):
    reqs = [grequests.post(url=url, headers=headers, json=json)
            for _ in range(num)]
    resps = grequests.map(reqs)
    for i, data in enumerate(resps):
        content_type = data.headers.get('Content-Type', '').lower()
        if data.status_code == 200 and content_type.startswith('application/json'):
            json_data = data.json()
            print(json_data)
            if 'status' in json_data:
                status = json_data['status']
                utc_now = datetime.utcnow().replace(tzinfo=timezone.utc)
 
                SHA_TZ = timezone(
                    timedelta(hours=8),
                    name='Asia/Shanghai',
                )
                beijing_now = utc_now.astimezone(SHA_TZ)
                print(beijing_now)
                now_fmt = beijing_now.strftime('%H:%M:%S:%f')
                print(now_fmt)
 
                if status == 301:
                    print(f"第{i + 1}个请求失败,状态码为301")
                    time.sleep(0.1)
                elif status == 500:
                    print(f"第{i + 1}个请求失败,状态码为500")
                    time.sleep(1)
                else:
                    print('成功')
                    return
            else:
                print(f"Error: json 响应里没有 'status' 字段")
        else:
            print(f"Error: 状态码 {data.status_code}, 响应格式 {content_type}")
 
 
def wait_until_8pm():
    target_time = datetime.now().replace(hour=7, minute=2, second=59, microsecond=504500)
    while True:
        now = datetime.now()
        if now >= target_time:
            break
        time.sleep(0.0001)
 
 
if __name__ == "__main__":
    wait_until_8pm()
    start_time = time.perf_counter()
    execute_command(10)
    end_time = time.perf_counter()
    print(f"耗时: {end_time - start_time:.6f} 秒")

最佳答案

查看完整内容

if __name__ == "__main__": while True: wait_until_8pm() start_time = time.perf_counter() execute_command(9) # 改为执行9次 end_time = time.perf_counter() print(f"耗时: {end_time - start_time:.6f} 秒") time.sleep(50) # 暂停50秒

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

rwj1990 发表于 2023-7-26 06:27
if __name__ == "__main__":
    while True:
        wait_until_8pm()
        start_time = time.perf_counter()
        execute_command(9)  # 改为执行9次
        end_time = time.perf_counter()
        print(f"耗时: {end_time - start_time:.6f} 秒")
        time.sleep(50)  # 暂停50秒
eclipsa 发表于 2023-7-26 07:07
那你写个变量记录一下次数,次数到了就time.sleep(50)就好了。
头像被屏蔽
zb848 发表于 2023-7-26 07:13
haimiandashu 发表于 2023-7-26 08:16
[Python] 纯文本查看 复制代码
import time
from datetime import datetime, timedelta, timezone
import grequests
from fake_useragent import UserAgent

url = 'https://www.baidu.com'
ua = UserAgent()
headers = {
    'Tyauthtoken': '4FE86EA2C64241BCA0220AFB0C517C2F',
    "User-Agent": ua.random
}

json_data = {
    # Your JSON data here
}

def execute_command(num=1):
    reqs = [grequests.post(url=url, headers=headers, json=json_data) for _ in range(num)]
    resps = grequests.map(reqs)
    for data in resps:
        content_type = data.headers.get('Content-Type', '').lower()
        if data.status_code == 200 and content_type.startswith('application/json'):
            json_data = data.json()
            if 'status' in json_data:
                status = json_data['status']
                if status == 301:
                    print("请求失败,状态码为301")
                    time.sleep(0.1)
                elif status == 500:
                    print("请求失败,状态码为500")
                    time.sleep(1)
                else:
                    print('成功')
            else:
                print("Error: json 响应里没有 'status' 字段")
        else:
            print(f"Error: 状态码 {data.status_code}, 响应格式 {content_type}")
    
    return True if num == 9 else False

def wait_until_8pm():
    target_time = datetime.now().replace(hour=7, minute=2, second=59, microsecond=504500)
    while True:
        now = datetime.now()
        if now >= target_time:
            break
        time.sleep(0.0001)

if __name__ == "__main__":
    wait_until_8pm()
    count = 0

    while True:
        start_time = time.perf_counter()
        completed = execute_command(9)
        end_time = time.perf_counter()
        print(f"本次循环耗时: {end_time - start_time:.6f} 秒")

        if completed:
            count += 1
            if count == 9:
                print("运行了9次,现在暂停50秒")
                time.sleep(50)
                count = 0
不知道改成啥 发表于 2023-7-26 08:32
你这是把论坛当GPT用啦
 楼主| sun4ay 发表于 2023-7-26 08:46
haimiandashu 发表于 2023-7-26 08:16
[mw_shl_code=python,true]import time
from datetime import datetime, timedelta, timezone
import gre ...

运行错误直接停止了
 楼主| sun4ay 发表于 2023-7-26 08:54
tanzhiwei 发表于 2023-7-26 08:32
你这是把论坛当GPT用啦

刚学习改改
Briller 发表于 2023-7-26 08:57
交给GPT
 楼主| sun4ay 发表于 2023-7-26 08:57
haimiandashu 发表于 2023-7-26 08:16
[mw_shl_code=python,true]import time
from datetime import datetime, timedelta, timezone
import gre ...

Traceback (most recent call last):
  File "C:\Users\Administrator\PycharmProjects\pythonProject\888.py", line 354, in <module>
    completed = execute_command(9)
  File "C:\Users\Administrator\PycharmProjects\pythonProject\888.py", line 315, in execute_command
    reqs = [grequests.post(url=url, headers=headers, json=json_data) for _ in range(9)]
  File "C:\Users\Administrator\PycharmProjects\pythonProject\888.py", line 315, in <listcomp>
    reqs = [grequests.post(url=url, headers=headers, json=json_data) for _ in range(9)]
NameError: free variable 'json_data' referenced before assignment in enclosing scope
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则 警告:本版块禁止回复与主题无关非技术内容,违者重罚!

快速回复 收藏帖子 返回列表 搜索

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2024-4-28 20:22

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表