如何使此代码运行得更好/更快(线程或多处理)?如何做到这一点?

2024-04-23 10:49:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个简单的机器人,它用cookies登录到一个站点,检查一个项目的价格,如果这个价格符合我设置的价格,它就会购买该项目。你知道吗

我正在寻找方法来提高这个机器人的速度。我真的不知道多重处理是否会使这个机器人在这种情况下更快。你知道吗

我也在寻找方法,使之更有效,如果有的话。你知道吗

session = requests.session()
session.cookies["cookie"] = ""

log_in = session.get("https://www.example.com")
if log_in.status_code == 200:
    print("Logged In")
else:
    raise ValueError("Invalid Cookie")

crsf_token = ""

def token():
    global crsf_token
    while True:
        crsf_token = re.search(r"<script>XsrfToken.setToken\('(.*?)'\);</script>", session.get('https://www.example.com').text).group(1)
        time.sleep(5)

def _cthread():
    while True:
        try:
            req = session.get(f"https://www.example.com/productID")
            if req.status_code == 429:
                time.sleep(5)
                continue

            for i in req.json()["data"]["Sellers"]:
                if i["Price"] <= 300:
                    session.post(f'https://www.example.com&expectedPrice={i["Price"]}&expectedSellerID={i["SellerId"]}&userAssetID={i["UserAssetId"]}', headers={"X-CSRF-TOKEN": crsf_token})
        except requests.urllib3.exceptions.ConnectTimeoutError as E:
            pass


while True:
    threading.Thread(target=_cthread).start()
    threading.Thread(target=token).start()

我没有得到太多的成功,但它现在确实工作。你知道吗


Tags: inhttpscomtokentruegetifexample
2条回答

尝试从函数token()&;_cthread()中删除while True

假设您没有带宽限制,并且站点不会一次关闭太多提交的POST,您可能会从线程化post调用中获得一些好处,更改:

        for i in req.json()["data"]["Sellers"]:
            if i["Price"] <= 300:
                session.post(f'https://www.example.com&expectedPrice={i["Price"]}&expectedSellerID={i["SellerId"]}&userAssetID={i["UserAssetId"]}', headers={"X-CSRF-TOKEN": crsf_token})

收件人:

        allposts = [f'https://www.example.com&expectedPrice={i["Price"]}&expectedSellerID={i["SellerId"]}&userAssetID={i["UserAssetId"]}'
                    for i in req.json()["data"]["Sellers"] if i["Price"] <= 300]
        if allposts:
            with Pool() as pool:
                pool.map(partial(session.post, headers={"X-CSRF-TOKEN": crsf_token}), allposts)

将以下导入添加到文件顶部:

from multiprocessing.dummy import Pool  # Gets thread based worker Pool class
from functools import partial           # Lets you bind headers up front so you only need to pass URL to post

为了避免产生过多的线程,可以在该函数的循环外创建pool,而不是仅在allposts非空时按需创建它。你知道吗

我还建议从代码的顶层删除while True:token_cthread都已经是无限循环了,所以拥有这两个循环意味着产生无限多的线程,每个线程永远运行,而实际上只需要两个持久线程。你知道吗

相关问题 更多 >