如何使用SeleniumWebDriver(Python)随机选择并单击元素?

如何使用SeleniumWebDriver(Python)随机选择并单击元素?,python,selenium,selenium-webdriver,robotframework,Python,Selenium,Selenium Webdriver,Robotframework,我必须从待办事项列表应用程序中随机选择一个元素,然后单击以删除它。基本上,每个元素都有相同的选择器,只是索引发生了变化,例如//*[@class=destroy][2]。 我有生成随机句子并将其添加到应用程序的代码。然后我必须随机选择一个元素->点击它删除,我被卡住了。选择一个随机数,实际上,它是有效的。但有时,如果随机选择[0],测试将失败,测试执行将花费大量时间,我相信有一种更专业的方法可以进行随机选择。你能告诉我其他可能的方法吗 from selenium import webdriver

我必须从待办事项列表应用程序中随机选择一个元素,然后单击以删除它。基本上,每个元素都有相同的选择器,只是索引发生了变化,例如//*[@class=destroy][2]。 我有生成随机句子并将其添加到应用程序的代码。然后我必须随机选择一个元素->点击它删除,我被卡住了。选择一个随机数,实际上,它是有效的。但有时,如果随机选择[0],测试将失败,测试执行将花费大量时间,我相信有一种更专业的方法可以进行随机选择。你能告诉我其他可能的方法吗

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver import ActionChains
import random
import os
 
@keyword
    def open_browser(self):
        os.environ['MOZ_HEADLESS'] = '1'
        self.driver = webdriver.Firefox()
        self.driver.get('http://todomvc.com/examples/react/#/')
        self.driver.implicitly_wait(20)
@keyword
    def generate_random_sentences(self, number, total_items_amount):
        words = [["One", "Two", "Three", "Four"], ["red", "yellow", "green", "blue"],
                 ["cats", "dogs", "zebras", "pandas"], ["jumped.", "danced.", "wrote poetry.", "cried."]]
        for i in range(int(number)):
            sentences = ' '.join([random.choice(w) for w in words])
            self.driver.find_element(By.CLASS_NAME, "new-todo").send_keys(sentences, Keys.ENTER)
        total_items = self.driver.find_element(By.CLASS_NAME, "todo-count")
        assert total_items.text == total_items_amount```

@keyword
    def delete_random_element(self, total_items_amount):
        i = random.choice(range(51))
        list_item = self.driver.find_element(By.XPATH, '(//*[@class="view"]){}'.format([i])) 
        hidden_button = self.driver.find_element(By.XPATH, '(//*[@class="destroy"]){}'.format([i])) 
        actions = ActionChains(self.driver)
        actions.move_to_element(list_item)
        actions.click(hidden_button)
        actions.perform()
        total_items = self.driver.find_element(By.CLASS_NAME, "todo-count")
        assert total_items.text == total_items_amount```
可以使用random.randintstart、end指定可以随机选择的整数范围,并将其作为索引传递

random_element = f'//*[@class="destroy"])[{random.randint(startint,endint)}]'
可以使用random.randintstart、end指定可以随机选择的整数范围,并将其作为索引传递

random_element = f'//*[@class="destroy"])[{random.randint(startint,endint)}]'