Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #Install selenium with pip install selenium
- #and make sure you place Chromedriver on the code path and latest Chrome Installed
- import selenium
- #used for sending keys
- from selenium.webdriver.common.keys import Keys
- #Used for Waiting for a xapth to be available
- from selenium.webdriver.support.ui import WebDriverWait
- from selenium.webdriver.support import expected_conditions as EC
- from selenium.webdriver.common.by import By
- #Initialize
- driver = webdriver.Chrome()
- URL= "www.amazon.in"
- #opening URL
- driver.get(URL)
- #finding element using xpath
- xpath_username = "//input[@id='username']" # 1. //- syntax find all elem , 2. input - tag , 3. @id - property , 4. "username" matching string
- xpath_password = "//input[@id='password']"
- xpath_login = "//button[@id='submit']"
- xpath_list = "//li[@class='menu']"
- driver.find_element_by_xpath(xpath_username)
- #Sending input data , sending to username field of the website. make sure Xpath is correctly mapping to input field
- driver.find_element_by_xpath(xpath_username).send_keys("arunkarnan")
- driver.find_element_by_xpath(xpath_password).send_keys("#########")
- #Clicking button
- driver.find_element_by_xpath(xpath_login).click()
- #Sometime we need to wait for JS to include certain elements or tags so we use Wait Method for it
- #Below code will wait until the page loas and shows username field "20" is timeout(Hot long to wait).
- WebDriverWait(driver,20).until(EC.presence_of_element_located((By.XPATH,xpath_username)))
- #You can find list of all elements using find_element<s>_by_xpath , this will return <web element> list
- driver.find_element_by_xpath(xpath_list)
- #YOu can get an elements attributes value by get_attribute('href') method with attribute key as parameters
- driver.find_element_by_xpath("//img").get_attribute('href')
- #Finally close the driver before finish otherwise I will keep on running in bg
- driver.close()
Add Comment
Please, Sign In to add comment