首页 > 解决方案 > 如何更快地运行 selenium webdriver 代码?

问题描述

如果有足够的库存,我制作了一个自动在亚马逊上购买商品的机器人。但它没有我想要的那么快。如何优化代码以更快地工作。任何帮助将不胜感激。

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.support.ui import Select
import winsound
import time


options = webdriver.ChromeOptions()
options.add_argument("user-data-dir=C:")
prefs = {"profile.managed_default_content_settings.images": 2}
options.add_experimental_option("prefs", prefs)



driver = webdriver.Chrome(executable_path="C:\\webdrivers\\chromedriver.exe", chrome_options=options)
buyingStatus = True

while(buyingStatus):
    try:
        driver.get("URL")
        beGreedy = Select(driver.find_element_by_id('quantity'))
        beGreedy.select_by_value('1')
        addCart = driver.find_element_by_id("add-to-cart-button").submit()
        completeTheShopping = driver.find_element_by_id("hlb-ptc-btn-native").click()
    

        buyNow = driver.find_element_by_xpath("html").click()


        freq = 500
        dur = 2000
        winsound.Beep(freq, dur)
        print("ITEM FOUND")
        buyingStatus = False

        

    except NoSuchElementException:
        print("Item doesn't exist")
        driver.refresh()
    
    

标签: pythonseleniumselenium-webdriverselenium-chromedriver

解决方案


您可以使用 webdriver waits 以 0.1 秒的间隔(轮询频率)检查按钮是否在某个时间 0.5 秒(我建议更高的数字)后存在。还将您的 driver.get() 拉到外面,然后使用 driver.refresh()。这还会检查您是否能够在最短的时间内使用您的元素。

我不确定它是否会自动更新,所以我不能只使用 webdriver wait 来检查它是否在没有 driver.refresh() 的情况下。

如果没有错误,也只需从您的方法中使用 break 。

另一个想法是无头运行它以进一步改进它。

wait = WebDriverWait(driver, 0.5, poll_frequency=0.1)
driver.get("URL")

while True:
    try:
       
        beGreedy = Select(wait.until(EC.element_to_be_clickable((By.ID, "quantity"))))
        beGreedy.select_by_value('1')        
        addCart = wait.until(EC.element_to_be_clickable((By.ID, "add-to-cart-button"))).submit()
        completeTheShopping = wait.until(EC.element_to_be_clickable((By.ID, "hlb-ptc-btn-native"))).click()
        buyNow = wait.until(EC.element_to_be_clickable((By.XPATH, "html"))).click()

        freq = 500
        dur = 2000
        winsound.Beep(freq, dur)
        print("ITEM FOUND")
        break        

    except Exception:
        print("Item doesn't exist")
        driver.refresh()

进口

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait 
from selenium.webdriver.support import expected_conditions as EC

推荐阅读