Home > Software engineering >  How to send a random text from a list through sendkeys() using Selenium and Python
How to send a random text from a list through sendkeys() using Selenium and Python

Time:07-24

I want selenium to randomly pick a text and then type it out.

Code:

driver.find_element (By.CSS_SELECTOR, '.editor-styles-wrapper .editor-post-title__input').send_keys("Granny Script")`

That is the element.

I would list the 5 texts for example "Hello, halal, no halal, hey, milk" and would like to randomly pick and type one of the sentences/words.

CodePudding user response:

import random

random_message = random.choice(['Hello', 'halal', 'no halal', 'hey', 'milk'])

driver.find_element (By.CSS_SELECTOR, '.editor-styles-wrapper .editor-post-title__input').send_keys(f"{random_message}") 

CodePudding user response:

random.choice(list) chooses a random item from a sequence. The seq can be a list, tuple, string or any iterable like range.

An example to send a random string from a list is as follows:

  • Code block:

    import random
    
    random_texts = ['Hello', 'halal', 'no halal', 'hey', 'milk']
    for i in range(3):
        print(random.choice(random_texts))
    
  • Console Output:

    halal
    milk
    no halal
    

This usecase

random_texts = ['Hello', 'halal', 'no halal', 'hey', 'milk']
driver.find_element (By.CSS_SELECTOR, '.editor-styles-wrapper.editor-post-title__input').send_keys(random.choice(random_texts))

PS: In CSS_SELECTOR the classnames should be appended through a dot (.) character and no additional spaces.

  • Related