Home > other >  Selenium Webdriver - Select Drop down, input text and click
Selenium Webdriver - Select Drop down, input text and click

Time:02-24

I got error: AttributeError: 'WebDriver' object has no attribute 'find_element_by'

url = "https://calculator.shipany.io/"
chrome_options = Options()
# chrome_options.add_argument("--headless")

driver = webdriver.Chrome(options=chrome_options)
driver.get(url)
sleep(5)

1.) How to use selenium to select drop down:

  • Select "Hong Kong" in Origin
origin = driver.find_element_by(By.XPATH, "//*[@id='i_form']/div/div[2]/div[1]/select/option[2]")
origin.click()
  • Select "Hong Kong" in Destination
destination = driver.find_element_by(By.XPATH, "//*[@id='i_form']/div/div[2]/div[2]/select/option[2]")
destination.click()

2.) How to input text in the placeholder of

  • weight
weight = driver.find_element_by(By.XPATH, "//*[@id='i_form']/div/div[2]/div[3]/input[1]")
weight.send_keys("1")
  • L(cm)
length = driver.find_element_by(By.XPATH, "//input[@placeholder='L(cm)']")
length.send_keys("1")
  • W(cm)
width = driver.find_element_by(By.XPATH, "//*[@id='dimension']/input[3]")
width.send_keys("1")
  • H(cm)
height = driver.find_element_by(By.XPATH, "//*[@id='dimension']/input[6]")
height.send_keys("1")

3.) How to click the button for submit-form?

button = driver.find_element_by(By.XPATH, "//*[@id='i_form']/div/div[2]/div[5]/button[1]")
button.click()

CodePudding user response:

Instead of find_element_by you should use find_element method.
Like

origin = driver.find_element(By.XPATH, "//*[@id='i_form']/div/div[2]/div[1]/select/option[2]")
origin.click()

etc.
You can reduce the code above to be

driver.find_element(By.XPATH, "//*[@id='i_form']/div/div[2]/div[1]/select/option[2]").click()

Also, you should use Expected Conditions explicit waits instead of hardcoded pauses like

sleep(5)

CodePudding user response:

The dropdown is Select component you can use Select class to access the element.

To handle dynamic element use explicit wait and wait for element to be visible.

driver.get("https://calculator.shipany.io/")
wait=WebDriverWait(driver, 5)
dropdownOrigin =wait.until(EC.visibility_of_element_located((By.XPATH, "//div[@class='booking-form']//select[.//option[contains(.,'Origin')]]")))
selectOrigin=Select(dropdownOrigin)
selectOrigin.select_by_visible_text("Hong Kong")

dropdownDestination =wait.until(EC.visibility_of_element_located((By.XPATH, "//div[@class='booking-form']//select[.//option[contains(.,'Destination')]]")))
selectDest=Select(dropdownDestination)
selectDest.select_by_visible_text("Hong Kong")

You need to import below libraries.

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

Browser snapshot: enter image description here

  • Related