Estoy tratando de raspar las preguntas y respuestas de este formularios de Google, que puedes encontrar en un csv para mi código:
Link, Task
https://docs.google.com/forms/d/1SrnftJ-u_G8rWJEkrF3TLvYMhX23G1bHHP8rQ3j8AfY, Hotel ABC
A veces necesito rellenar el formulario de Google para poder hacer clic en el siguiente botón. Desafortunadamente parece que no puedo hacer clic en las últimas casillas de verificación. Así que estoy atascado en un bucle. Aquí está mi código:
from collections import defaultdict
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import ElementClickInterceptedException
import time
from selenium.webdriver.chrome.options import Options
from selenium.common.exceptions import NoSuchElementException
import pandas as pd
from selenium.common.exceptions import ElementNotInteractableException, NoSuchElementException
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
import pickle
def setup_chromedriver():
chrome_options = Options()
# chrome_options.add_argument("--headless")
# driver = webdriver.Chrome(ChromeDriverManager().install())
driver = webdriver.Chrome("C:\Programs\chromedriver.exe")
return driver
def load_data():
df = pd.read_csv("research.csv")
filter_col = ["Link"]
return df, filter_col
def get_published_questionnaire():
questionnaire = {}
containers = driver.find_elements_by_class_name(
"freebirdFormviewerViewNumberedItemContainer"
)
btns = driver.find_elements_by_css_selector(".appsMaterialWizButtonEl")
for container in containers:
try:
question = container.find_element_by_class_name(
"freebirdFormviewerViewItemsItemItemTitle"
)
except NoSuchElementException:
continue
responses = container.find_elements_by_class_name(
"docssharedWizToggleLabeledLabelText"
)
extracted_text = [response.text for response in responses]
questionnaire[question.text] = extracted_text
# # write answers when compulsory
# content_areas = driver.find_element_by_css_selector(
# "input[type='date']"
# )
# for content_area in content_areas:
# content_area.send_keys("10102015")
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")
content_areas = driver.find_elements_by_class_name(
"docssharedWizToggleLabeledContainer.freebirdFormviewerViewItemsRadioChoice"
)
btns_answers = driver.find_elements_by_css_selector(".appsMaterialWizToggleRadiogroupElContainer")
for btns_answer in btns_answers:
try:
driver.execute_script('arguments[0].scrollIntoView(true);', btns_answer)
btns_answer.click()
except ElementNotInteractableException:
pass
# 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
btns[-1].click()
return questionnaire
def get_backend_questionnaire():
questionnaire = {}
# I get all the card with questions and answers inside
containers = driver.find_elements_by_class_name(
"freebirdFormeditorViewItemcardRoot.item-dlg-affectsIndex.item-dlg-dragTarget"
)
# for each card
for container in containers:
try:
# Get the question
question = container.find_element_by_class_name(
"appsMaterialWizTextinputTextareaInput.exportTextarea"
)
except NoSuchElementException:
print("NoSuchElementException: ")
continue
# Get the answers
responses = container.find_elements_by_class_name(
"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)
return questionnaire
def extract(driver, df, survey):
# locations = df[column].iteritems()
count = 0
result = []
for location, task in zip(df.Link, df.Task):
print("location: ", location)
print("task: ", task)
if task == survey:
questionnaire = {}
if "docs.google.com" in str(location):
location = location
driver.get(location)
# test if it is a published version
ask_access_btn = driver.find_elements_by_class_name(
"freebirdFormviewerViewNavigationHeaderButtonContent"
)
if ask_access_btn:
published_questionnaires.append(location) # storing published questionnaire
questionnaire = get_published_questionnaire()
else:
questionnaire = get_backend_questionnaire()
result.append({count: questionnaire})
count += 1
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()
""" Load CSV download of Google Sheet """
df, columns = load_data()
surveys = ['Hotel ABC']
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()
Y nunca logro hacer clic en los siguientes chexboxes: