简体   繁体   中英

How to Handle Drop-down for Google form using selenium using python

can someone help me on how to automate the dropdown menu in google form using selenium in python. the problem that I am facing is I am able to locate the drop down menu and select it but I am not able to select the options I have tried select_by_index but it doesn't work. thank you in advance. (I am new to the forum so sorry if I have asked the question in a ambiguous way)

drop = Select(browser.find_element_by_class_name('quantumWizMenuPaperselectContent').click())
drop.select_by_index(0)

Although I think there may be better ways to do it, I manage to do it this way:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome("YOUR PATH HERE")
driver.get("YOUR SITE HERE")
driver.find_element(By.CSS_SELECTOR, ".isSelected").click()

# Item 1 in drop down has an ending Div of 3
# Item 2 ending div of 4 
# I added the + 2 in the f string so that DROPDOWN_ITEM = 1 Means find for div 3

DROPDOWN_ITEM = 1
dropdown_item_1 = WebDriverWait(driver, 10).until(EC.presence_of_element_located
                                       ((By.XPATH, f'//*[@id="mG61Hd"]/div[2]/div/div[2]/div/div/div/div[2]/div/div[2]/div[{DROPDOWN_ITEM} + 2]')))

dropdown_item_1.click()

if you would just like to target the first item, can use something like this:

dropdown_item_1 = WebDriverWait(driver, 10).until(EC.presence_of_element_located
                                       ((By.XPATH, '//*[@id="mG61Hd"]/div[2]/div/div[2]/div/div/div/div[2]/div/div[2]/div[3]')))

dropdown_item_1.click()

Without using Select, here is how I managed to do it.

Since google forms are TAB friendly (ie, you can navigate top to bottom using the TAB key), you can select the previous field and do send_keys(Keys.TAB) to focus the target field...

example:-

url = "https://docs.google.com/forms/d/e/1FAIpQLScosZjmDrvgUvh77tXsaAb24hKVgaBnjJfJz2BX1PvoqIO1Ow/viewform"

phField = #xpath of phone number field

now, focusing on the next field of phField, and sending the needed option.

driver.find_element_by_xpath(phField ).send_keys(Keys.TAB,"10.05")

don't forget to import Keys from selenium.webdriver.common.keys

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM