簡體   English   中英

如何隨機 select 並使用 selenium webdriver(Python)單擊元素?

[英]How to randomly select and click on element with selenium webdriver (Python)?

我必須從待辦事項列表應用程序中隨機 select 一個元素,然后單擊以將其刪除。 基本上,每個元素都有相同的選擇器,只是索引更改(例如//*[@class="destroy"])[2])。 我有生成隨機句子並將它們添加到應用程序的代碼。 然后我必須隨機 select 一個元素 -> 點擊它刪除,我就卡在這里了。 Random.choice 選擇一個隨機數,實際上它可以工作。 但有時如果它隨機選擇 [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.randint(start, end)指定可以隨機選擇的整數范圍並將其作為索引傳遞。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM