Estoy tratando de raspar las preguntas y respuestas de un archivo csv de [formularios de Google][1], que puedes encontrar en un csv para mi código:

    Link,Task
    https://docs.google.com/forms/d/1MYSjxAMCXMXB02GPXqkewVx35_ptzv0XO7GRZQGwyGE/edit?usp=sharing,Hotel ABC
    https://docs.google.com/forms/d/1VQpzX1GqsnI92J1trlP37v3GjVgNMp1h-1Rh_n8orII/edit?usp=sharing,Airline XYZ
    https://docs.google.com/forms/d/1z-qyHp7O4eTI848b6L8_vh59IJ-y0bFpAo--zwPKJxY/edit?usp=sharing,Airline XYZ
    https://docs.google.com/forms/d/1IoDbsif5qorINuUrF1Dl9iMtIdnAsTvVA3vMVsVHjy8/edit?usp=sharing,Airline XYZ

Trato de obtener las preguntas y respuestas del cuestionario para meterlas en un archivo csv que se parece al siguiente:

    pickle_file_name,id,question,answer_1,answer_2,answer_3,answer_4,answer_5,answer_6,answer_7,answer_8,answer_9,answer_10,answer_11,answer_12,answer_13,answer_14
    applicantHotel_ABC_c,1,How do you feel about your next vacation after COVID-19?,,,,,,,,,,,,,,
    applicantHotel_ABC_c,2,When do you think your next vacation can start?,In next 3 months,In next 6 months,In next 1 year,Only once COVID-19 is under control,Only once COVID-19 vaccine is developed,,,,,,,,,
    applicantHotel_ABC_c,3,What are your preferences regarding medical treatment policy (with additional cost)?,Doctor's availability in hotel,Ventilator availability in hotel,Tie-ups with nearby hospitals,Availability of medical rooms with primary first aid care,,,,,,,,,,
    applicantHotel_ABC_c,4,What is your preferences of complementary breakfast?,Buffet breakfast with social distancing,Buffet breakfast replaced with Ala-carte with limited options,Breakfast to be delivered in room with limited options (chargeable),Packaged breakfast only,,,,,,,,,,

Sin embargo, hay dos tipos de cuestionarios, los que se publican (los formularios de Google que enfrentamos en la vida real) y aquellos para los que tenemos acceso al backend. Si puedo hojear ambos tipos de cuestionarios, no puedo obtener las preguntas de las preguntas publicadas.

En efecto obtengo los siguientes tipos de exceptiones:

 - `UnexpectedAlertPresentException`: es porque parece que hay el boton para modificar el  `location:  https://docs.google.com/forms/d/1HAMUvDpYiz-SpQpKwUOxyHqn3Be7OV9vLER3K5ltrxg/edit?usp=sharing
UnexpectedAlertPresentException`
 - `content_area.get_attribute("aria-label")`: Me siento como si estuviera repitiendo una y otra vez sobre la misma cosa.

¡Basta de hablar! Aquí está mi código que te permite obtener un poco más del 5% de los formularios de Google:

    from selenium import webdriver
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    import time
    import pandas as pd
    from selenium.common.exceptions import ElementNotInteractableException, NoSuchElementException
    from selenium.webdriver.chrome.options import Options
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.common import exceptions
    import pickle
    
    
    WDWTIME = 20
    USER = '[email protected]' # ciertos google forms le requieren
    PWD = "yourpassword"
    def setup_chromedriver():
        chrome_options = Options()
        chrome_options.add_argument("--headless")
        driver = webdriver.Chrome("C:\Programs\chromedriver.exe")
        """Some of the google forms need a login"""
        url = 'https://www.google.com/accounts/'
        driver.get(url)
        # Find login field
        login_field = WebDriverWait(driver, WDWTIME).until(
            EC.presence_of_element_located((By.ID, 'identifierId')))
        login_field.send_keys(USER)
        # Click next button
        driver.find_element_by_id('identifierNext').click()
        # Find password field
        time.sleep(4)
        driver.set_page_load_timeout(50)
        driver.set_script_timeout(50)
        password_field = WebDriverWait(driver, WDWTIME).until(
            EC.presence_of_element_located((By.ID, 'password')))
        password_field = password_field.find_element_by_tag_name('input')
        password_field.send_keys(PWD)
        # Click next button
        driver.find_element_by_id('passwordNext').click()
        driver.set_page_load_timeout(30)
        driver.set_script_timeout(30)
        return driver
    
    
    def load_data():
        df = pd.read_csv("research_assistant_intern_recruitment_an.csv")
        filter_col = ["Link"]
        return df, filter_col
    
    
    def get_published_questionnaire():
        print("published questionnaire")
        questionnaire = {}
        btns = driver.find_elements_by_css_selector(".appsMaterialWizButtonEl")
        # get "next" button, *warning* "request edit access" is also catched
        next_btns = driver.find_elements_by_class_name("appsMaterialWizButtonPaperbuttonContent.exportButtonContent")
        if next_btns:
            next_btns[-1].click()
            next_btns = driver.find_elements_by_class_name("appsMaterialWizButtonPaperbuttonContent.exportButtonContent")
            while next_btns != []:
                containers = driver.find_elements_by_class_name(
                    "freebirdFormviewerViewNumberedItemContainer"
                )
                len_containers = len(containers)
                for container in containers:
                    len_containers -=1
                    print("len_containers: ", len_containers)
                    try:
                        question = container.find_element_by_class_name(
                            "freebirdFormviewerViewItemsItemItemTitle.exportItemTitle.freebirdCustomFont"
                        )
                    except NoSuchElementException:
                        print("No question, NoSuchElementException")
                        continue
                    except exceptions.StaleElementReferenceException:
                        print("No question, StaleElementReferenceException")
                        continue
    
                    responses = container.find_elements_by_class_name(
                        "docssharedWizToggleLabeledLabelText"
                    )
                    extracted_text = [response.text for response in responses]
                    questionnaire[question.text] = extracted_text
                    content_areas = driver.find_elements_by_class_name(
                        "quantumWizTextinputSimpleinputInput.exportInput"
                    )
                    for content_area in content_areas:
                        skip = ["Document title", "Titre du document", "Adresse e-mail valide"]
                        if content_area.get_attribute("aria-label") in skip and not content_area.get_attribute("aria-label").isspace():
                            print("content_area.get_attribute(\"aria-label\"): ", content_area.get_attribute("aria-label"))
                        else:
                            print("content_area.get_attribute(\"aria-label\"): ", content_area.get_attribute("aria-label"))
                            content_area.send_keys("10102015")
    
                    content_areas = driver.find_elements_by_class_name(
                        "quantumWizTextinputPaperinputInput.exportInput"
                    )
                    for content_area in content_areas:
                        if content_area.get_attribute("type") == "date" and not content_area.get_attribute("type").isspace():
                            condition = content_area.get_attribute("type")
                            if condition == "date":
                                content_area.send_keys("10102015")
                        elif content_area.get_attribute("max") and not content_area.get_attribute("max").isspace():
                            max = content_area.get_attribute("max")
                            content_area.send_keys(max)
                        elif content_area.get_attribute("aria-label") and not content_area.get_attribute("aria-label").isspace():
                            condition = content_area.get_attribute("aria-label")
                            print("content_area.get_attribute(\"aria-label\"): ", content_area.get_attribute("aria-label"))
                            if condition == "State (Two letter Abbreviation)":
                                content_area.send_keys("CA")
                            else:
                                content_area.send_keys("10102015")
    
                    for content_area in content_areas:
                        skip = ["Document title", "Titre du document", "Adresse e-mail valide"]
                        if content_area.get_attribute("aria-label") in skip and not content_area.get_attribute("aria-label").isspace():
                            print("content_area.get_attribute(\"aria-label\"): ", content_area.get_attribute("aria-label"))
                        else:
                            print("content_area.get_attribute(\"aria-label\"): ", content_area.get_attribute("aria-label"))
                            content_area.send_keys("10102015")
                    btns_answers = driver.find_elements_by_css_selector(".appsMaterialWizToggleRadiogroupElContainer")
                    for btn_answer in btns_answers:
                        try:
                            driver.execute_script('arguments[0].scrollIntoView(true);', btn_answer)
                            btn_answer.click()
                        except ElementNotInteractableException:
                            pass
                        except exceptions.ElementClickInterceptedException:
                            continue
    
                    # long answers
                    content_areas = driver.find_elements_by_class_name(
                        "quantumWizTextinputPapertextareaInput.exportTextarea"
                    )
                    for content_area in content_areas:
                        content_area.send_keys("This restaurant is really good! Me and my boyfriend went there on our holiday \
                            we had dinner there at 3 of February food was 100% And the service vas 150% And i really want to thank "
                                               "\Asie for a really good service as for his coworkers. We highly recommended \
                                               this restaurant!")
    
                    # check boxes
                    btn_check_boxes = driver.find_elements_by_class_name(
                        "docssharedWizToggleLabeledContainer.freebirdFormviewerViewItemsCheckboxContainer"
                    )
                    for btn_check_box in btn_check_boxes:
                        btn_check_box.click()
                        break
                    # btn_check_box[-1].click()
    
                    # # other weird check boxes
                    btn_check_boxes = driver.find_elements_by_class_name(
                        "docssharedWizToggleLabeledLabelText.exportLabel.freebirdFormviewerViewItemsCheckboxLabel"
                    )
                    for btn_check_box in btn_check_boxes:
                        btn_check_box.click()
                        break
                    # btns[-1].click()
                    next_btns = driver.find_elements_by_class_name(
                        "appsMaterialWizButtonPaperbuttonContent.exportButtonContent")
                    if next_btns != []:
                        next_btns[-1].click()
                        next_btns = []
                    else:
                        continue
    
        print("questionnaire: ", questionnaire)
        return questionnaire
    
    
    def get_backend_questionnaire():
        print("backend questionnaire")
        # sometimes we start with something that looks like a published page with a "next" button
        # if driver.find_element_by_id('identifierNext'):
        #     driver.find_element_by_id('identifierNext').click()
        questionnaire = {}
        # I get all the cards with questions and answers inside
        containers = driver.find_elements_by_class_name(
            "freebirdFormeditorViewItemContentWrapper"
        )
        driver.set_page_load_timeout(30)
        driver.set_script_timeout(30)
        # for each card
        for container in containers:
            try:
                # Get the question
                # question = container.find_element_by_class_name(
                #     "appsMaterialWizTextinputTextareaInput.exportTextarea"
                # )
                question = container.find_element_by_css_selector(".exportTextarea[aria-label='Intitulé de la question']")
            except NoSuchElementException:
                print("NoSuchElementException in " + str(container))
                continue
            # Get the answers
            responses = container.find_elements_by_css_selector(
                ".quantumWizTextinputSimpleinputInput.exportInput"
            )
            extracted_responses = [response.get_attribute("data-initial-value") for response in responses]
            questionnaire[question.text] = extracted_responses
    
            driver.set_page_load_timeout(30)
            driver.set_script_timeout(30)
    
        print("questionnaire backend: ", questionnaire)
        return questionnaire
    
    
    def extract(driver, df, survey):
        count_questionnaires = 0
        result = []
        count_not_empty = 0.0
        print("survey: ", survey)
        for location, task in zip(df.Link, df.Task):
            if task == survey:
                print("location: ", location)
                questionnaire = {}
                if "docs.google.com" in str(location):
                    count_questionnaires +=1.0
                    driver.get(location)
                    # test if it is a published version
                    try:
                        ask_access_btn = driver.find_elements_by_class_name(
                            "freebirdFormviewerViewNavigationHeaderButtonContent"
                            )
                    except exceptions.UnexpectedAlertPresentException:
                        print("UnexpectedAlertPresentException")
                        get_published_questionnaire
                    if ask_access_btn:
                        questionnaire = get_published_questionnaire()
                    else:
                        questionnaire = get_backend_questionnaire()
                if questionnaire not in [{}, {'': ''}]:
                    count_not_empty += 1.0
                print(questionnaire)
                result.append({str(count_questionnaires): questionnaire})
                count_questionnaires += 1
        print("count_questionnaires: ", count_questionnaires)
        if count_questionnaires != 0:
            print("count_not_empty/count_questionnaires: ", count_not_empty/count_questionnaires)
        return result
    
    
    if __name__ == '__main__':
        """ Need to log on to the google account to access certain questionaires. Also Setup chromedriver to run in 
        headless state """
        driver = setup_chromedriver()
        published_questionnaires = [] # tracking published ones
        """ Load CSV download of Google Sheet """
        df, columns = load_data()
        surveys = ['Hotel ABC', "Airline XYZ", "The Ministry of Tourism of France"]
        for survey in surveys:
            result = extract(driver, df, survey)
            survey = survey.replace(" ", "_")
            pickle_out = open("applicant" + survey + "_c.p", "wb")
            pickle.dump(result, pickle_out)
            pickle_out.close()
        print("published_questionnaires: ", published_questionnaires)


  [1]: https://docs.google.com/forms/d/1SrnftJ-u_G8rWJEkrF3TLvYMhX23G1bHHP8rQ3j8AfY
  [2]: https://i.sstatic.net/jt5cO.png