[英]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.