The latest python implements the questionnaire star brush questionnaire, Edge version

Recently, a friend asked me to write a questionnaire. I thought that my friend has been doing questionnaires recently (the smart verification code was copied from him), thinking that it is better to ask others than to ask yourself, so I made this code in two days.

The code implements the answer of the single-choice multiple-choice fill-in-the-blank drop-down box scale matrix question type. In fact, the principles of other question types are similar, but these types are basically the only ones in the market. Each question can set its own probability, (multiple-choice questions are more complicated, and I basically don’t need to comment on them)

Because I usually like to use edge and the current Google version of the code is very complete, so I put the code of my edge version up (actually it’s just a name change)

from selenium import webdriver
import time
from selenium.webdriver.edge.service import Service
from selenium.webdriver.common.action_chains import ActionChains
import random
from selenium.webdriver.common.by import By

"""
It is only used for testing and self-study, please do not use it for academic cheating or other illegal activities.
At present, no verification problems have been found, covering 90% of the mainstream question types in the market, and the modification of the ip address will be updated later
If you want to learn or have operational problems, please contact me
"""

# Scroll the page
def scroll(driver, distance):
    js = f"var q=document.documentElement.scrollTop={distance}"
    driver. execute_script(js)


# Multiple Choice Questions
def single_choice(driver, num):
    # find all multiple choice questions
    questions = driver.find_elements(By.CSS_SELECTOR, f'#div{num} > div.ui-controlgroup.column1')
    for question in questions:
        options = question.find_elements(By.CSS_SELECTOR, '.ui-radio')
        weights = [3, 7] # The weight of the first option is 7, and the weight of the second option is 3
        selected_option = random.choices(options, weights=weights)[0]
        selected_option. click()
        time. sleep(random. randint(0, 1))

# drop down box
def xialakuang(driver, num):
    # Find the dropdown box element
    driver.find_element(By.XPATH, f'//*[@id="select2-q{num}-container"]').click()
    # Get all options
    options = driver.find_elements(By.CSS_SELECTOR, '.select2-results__option')

    weights = [0,0.1,0.9] #default the first "please choose" is not selected, the latter is the probability
    # choose a random option
    random_option = random.choices(options, weights=weights)[0]
    # click options
    random_option. click()
    time. sleep(random. randint(0, 1))

# multiple choice questions
def multiple_choice(driver, num):
    # def multiple_choice(driver, num): used when asked to set combination probability
    # # Find all multiple choice questions
    # questions = driver.find_elements(By.CSS_SELECTOR, f'#div{num} > div.ui-controlgroup.column1')
    # for question in questions:
    # options = question. find_elements(By. CSS_SELECTOR, '.ui-checkbox')
    #
    # # Set different weights for different combinations of options
    # weighted_options = [
    # (('A', 'B'), 10),
    # (('B',), 90),
    # ]
    #
    # # Use weights to randomly select an option combination
    #selected_option_combination = \
    # random. choices(weighted_options, weights=[w for _, w in weighted_options], k=1)[0][0]
    #
    # # Select options based on the selected option combination
    # for i, option in enumerate(options):
    # option_text = option.text
    # if option_text in selected_option_combination:
    # if not option. is_selected():
    # option. click()
    # time. sleep(random. randint(0, 1))

    # Usually use this
        questions = driver.find_elements(By.CSS_SELECTOR, '#div2 > div.ui-controlgroup.column1')
        for question in questions:
            options = question.find_elements(By.CSS_SELECTOR, '.ui-checkbox')
            num_choices = random. randint(1, len(options))
            selected_options = random. sample(options, num_choices)
            for option in selected_options:
                if not option.is_selected():
                    option. click()
                    time. sleep(random. randint(0, 1))



# fill in the blank
def fill_in_the_blank(driver, num):
    index = ["A", "B", "C"]
    answers = {"A": "Python is really easy to use!", "B": "This test was a success!", "C": "Fill in the blanks with random text"}

    weights = [0, 0.5, 0.5] # Assign weights to each answer in order
    # Choose the answer based on the weight value
    selected_answer = random.choices(list(answers.values()), weights=weights)[0]
    # fill in the corresponding answer
    driver.find_element(By.CSS_SELECTOR, f'#q{num}').send_keys(selected_answer)

    time. sleep(random. randint(0, 1))

# matrix question
def juzhen(driver, num):
    num_dimensions = 2 # Set the number of dimensions, adjust according to the actual situation

    weights_list = [
        [0, 0, 0,0.5,0.5], # list of option weights for the first dimension
        [0.5, 0.5, 0,0,0] # List of option weights for the second dimension
    ]

    for i in range(1, num_dimensions + 1):
        options = driver.find_elements(By.XPATH, f'//*[@id="drv{num}_{i}"]/td/a')
        weights = weights_list[i - 1] # Select the corresponding weight list according to the index of the current dimension

        selected_option = random.choices(options, weights=weights)[0]
        selected_option. click()

        time. sleep(random. randint(0, 1))



# two table questions
def liangbiao(driver, num):
    options = driver.find_elements(By.XPATH, f'//*[@id="div{num}"]/div[2]/div/ul/li')

    weights = [0, 0, 0,0.5,0.5] # Assign the weight value of the option, corresponding to the options list in order

    selected_option = random.choices(options, weights=weights)[0]
    selected_option. click()
    time. sleep(random. randint(0, 1))

# resolve validation
def yanzheng(driver):
    try:
        time.sleep(1) # Wait for the verification to pop up
        # Click the confirm button of the dialog
        driver.find_element(By.XPATH, '//*[@id="layui-layer1"]/div[3]/a').click()
        time.sleep(4) # Confirm verification time
        # Click the smart detection button
        driver.find_element(By.XPATH, '//*[@id="SM_BTN_1"]').click()
        time.sleep(4) # Intelligent monitoring time
    except:
        print("No verification")
    # slider validation
    # At present, the probability of slider verification is very low. Generally, you can directly close the service and re-refresh to solve it. The situation of slider has not yet been encountered.
    try:
        slider = driver. find_element(By. XPATH, '//*[@id="nc_1__scale_text"]/span')
        if str(slider.text).startswith("Please press and hold the slider"):
            width = slider. size. get('width')
            ActionChains(driver).drag_and_drop_by_offset(slider, width, 0).perform()
    except:
        pass

# start up!
def qd(times):
    url = 'https://www.wjx.cn/vm/e8pnohT.aspx# ' # Incoming link of questionnaire star
    # driver.set_window_size(600, 400) #Set window size
    driver_path = r"C:\Users\lenovo\Music\edgedriver_win64\msedgedriver.exe" # pass in the path of edgedriver
    options = webdriver. EdgeOptions()
    options.add_argument("--disable-blink-features=AutomationControlled")
    options.binary_location = r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe" # pass in the path of edge

    for i in range(times):
        # Avoid smart detection, set webDriver to false
        option = webdriver. EdgeOptions()
        option.add_experimental_option('excludeSwitches', ['enable-automation'])
        option. add_experimental_option('useAutomationExtension', False)

        service = Service(driver_path)
        service. start()
        driver = webdriver. Edge(service=service, options=options)

        try:
            driver. get(url)



            #running area
            single_choice(driver, 1)
            multiple_choice(driver, 2)
            fill_in_the_blank(driver, 3)
            xialakuang(driver, 4)
            scroll(driver, 300)
            juzhen(driver, 5)
            scroll(driver, 600)
            liangbiao(driver,6)
            time. sleep(random. randint(0, 1))


            driver.find_element(By.CSS_SELECTOR, '#ctlNext').click()
            yanzheng (driver)
            time. sleep(2)

            print(f'has submitted {i + 1} questionnaires')
        except Exception as e:
            print(f'An exception occurred: {str(e)}')
        finally:
            driver. quit()
            service. stop()

if __name__ == "__main__":
    qd(5)

This is the first post I followed to learn (47 messages) Using Python to realize the automatic filling of questionnaire stars (super detailed!!!)

This is written by my good brother. His code is very perfect (although I feel that mine is better to understand) adding ip change, and my verification function is changed from his function.

(47 messages) python + selenium, brush questionnaire stars, support ip + ratio, no need to change the code, set ip + ratio to run_black^sugar’s blog-CSDN blog