[英]How can I make this code run better/faster (threading or multiprocessing)? And how can it be done?
我有一个简单的机器人,它使用Cookie登录到站点并检查商品的价格,如果该价格符合我设置的价格,它将购买商品。
我正在寻找提高该机器人速度的方法。 我真的不知道在这种情况下,多处理是否会使该机器人更快。
我也在寻找提高效率的方法。
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()
我在这方面并没有获得太大的成功,但是它确实可以正常工作。
尝试从函数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
为非空时按需创建pool
。
我还建议从代码的顶层删除while True:
token
和_cthread
都已经是无限循环,因此拥有两个循环意味着产生了无限数量的线程,当您确实只需要两个持久性线程时,每个线程将永远运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.