how to select an item of a dropdown using selenium in python - python

I'm trying to click on "Universität Bern" which is an option of a dropdown that can be found in the following link:
I used the following code to get to the page (link), but I'm not able to click on an opetion of this dropdown. My code is :
import content as content
from selenium import webdriver
from selenium.webdriver.support.ui import Select
import time
path = "C:\Program Files\chromedriver.exe"
driver = webdriver.Chrome(path)
driver.get("https://www.zssw.unibe.ch/usp/zms/angebot/6728/index_ger.html")
pathanmelden = driver.find_element_by_xpath("//*
[#id='content']/section/div/div/div/div/div/table/tbody/tr[5]/td[2]/a")
pathanmelden.click()
time.sleep(1)
pathforstudents = driver.find_element_by_xpath("/html/body/div/div[2]/div[2]/form/input")
pathforstudents.click()
chosetheuniversity = driver.find_element_by_class_name("")# This is what does not work"
I appreciate any help.

This drop down is not build using select and option tag so select class won't work.
You should first click on drop down arrow and then click on the desired element.
Code:
driver.maximize_window()
wait = WebDriverWait(driver, 30)
driver.get("https://www.zssw.unibe.ch/usp/zms/angebot/6728/index_ger.html")
pathanmelden = driver.find_element_by_xpath("//* [#id='content']/section/div/div/div/div/div/table/tbody/tr[5]/td[2]/a")
pathanmelden.click()
time.sleep(1)
pathforstudents = driver.find_element_by_xpath("/html/body/div/div[2]/div[2]/form/input")
pathforstudents.click()
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "img#user_idp_iddicon"))).click()
time.sleep(2)
wait.until(EC.element_to_be_clickable((By.XPATH, "//div[#title='Universities: Universität Bern']"))).click()
Imports:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
PS: I have not changed your existing locators, you can change them as well since they are absolute xpath. time.sleep(2) is just for visualization purposes. You can remove that once you test out the code.

Try Following by sending your text then press Enter:
Java Code:
WebDriver driver;
WebDriverManager.chromedriver().setup();
ChromeOptions options = new ChromeOptions();
options.addArguments("disable-infobars");
driver = new ChromeDriver(options);
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(30, 1));
driver.manage().window().maximize();
driver.get("https://www.zssw.unibe.ch/usp/zms/login.php?");
By y = By.xpath("//INPUT[#id='user_idp_iddtext']");
driver.findElement(y).clear();
Thread.sleep(2);
driver.findElement(y).sendKeys("Universität Bern");
Thread.sleep(2);
driver.findElement(y).sendKeys(Keys.ENTER);
Python:
driver.maximize_window()
wait = WebDriverWait(driver, 30)
driver.get("https://www.zssw.unibe.ch/usp/zms/angebot/6728/index_ger.html")
x= driver.find_element_by_xpath("//INPUT[#id='user_idp_iddtext']")
x.clear()
time.sleep(1)
x.send_Keys("Universität Bern")
time.sleep(1)
x.send_Keys(Keys.ENTER)

Related

Selecting a specific element with Selenium - Python

I'm trying to click this button shown after choosing an option from a drop-down menu.
This is the button I'm trying to click.
The link to the website: https://excise.wb.gov.in/CHMS/Public/Page/CHMS_Public_Hospital_Bed_Availability.aspx
The html:
I've tried using XPATH, and through visible text; nothing seems to work.
My code as of now:
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
from selenium.webdriver.support.ui import Select
PATH = "C:\Program Files (x86)\chromedriver.exe"
driver = webdriver.Chrome(PATH)
driver.get("https://excise.wb.gov.in/CHMS/Public/Page/CHMS_Public_Hospital_Bed_Availability.aspx")
drop_dist = \
driver.find_element(By.XPATH, "/html/body/form/div[3]/main/div[2]/div/div[2]/div/div[1]/div[2]/div/select")
select_dist = Select(drop_dist)
select_dist.select_by_value("005")
l = driver.find_element(By.XPATH, "/html/body/form/div[3]/main/div[2]/div/div[2]/div/div[4]/div/div/table/tbody/tr[1]/td/div/div[2]/div[2]/div[1]/a").click()
time.sleep(30)
Any help is much appreciated!
The locator seems fragile, use following locator and webdriverwait() to handle sync issue.
driver.get("https://excise.wb.gov.in/CHMS/Public/Page/CHMS_Public_Hospital_Bed_Availability.aspx")
wait=WebDriverWait(driver, 20)
select_dist =Select(wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "#ctl00_ContentPlaceHolder1_ddl_District"))))
select_dist.select_by_value("005")
wait.until(EC.element_to_be_clickable((By.XPATH, "(//a[#class='btn btn-link' and contains(., 'View Detail Break up')])[1]"))).click() //this will click the first one only.
You have to add following imports.
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
Try this:
button = driver.find_elements(By.CSS, 'a[role="button"][aria-expanded="false"]')[0]
button.click()
You can change the index in order to click on other elements

Dropdown option not getting selected using Selenium Python

I am trying to select a dropdown option in the form using Selenium webdriver in Python. The XPATH is correct, I also verified it is going to the right dropdown option but in the end it is not selecting it.
I have tried similar code for another website that has a dropdown. But it's not working for this particular website.
Can someone please help out with this?
from selenium import webdriver
driver = webdriver.Chrome("C:\\Users\\xxx\\Downloads\\chromedriver_win32\\chromedriver.exe")
driver.get("https://www.cersai.org.in/CERSAI/dbtrsrch.prg")
elem = driver.find_element_by_xpath("//select[#id='borrowerType']")
all_options = elem.find_elements_by_tag_name("option")
for option in all_options:
if option.get_attribute("value") == "IND":
option.click()
break
You should add a wait before accessing the dropdown element to make it loaded.
Also, this is a Select element, you can treat it in a special way as below:
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("C:\\Users\\xxx\\Downloads\\chromedriver_win32\\chromedriver.exe")
wait = WebDriverWait(driver, 20)
driver.get("https://www.cersai.org.in/CERSAI/dbtrsrch.prg")
wait.until(EC.visibility_of_element_located((By.XPATH, "//select[#id='borrowerType']")))
select = Select(driver.find_element_by_xpath("//select[#id='borrowerType']"))
# select by visible text
select.select_by_value('IND')
It's strange that Select class did not work. It needs a JavaScript call.
driver = webdriver.Chrome(driver_path)
driver.maximize_window()
driver.implicitly_wait(50)
driver.get("https://www.cersai.org.in/CERSAI/dbtrsrch.prg")
driver.execute_script("return document.getElementById('borrowerType').selectedIndex = '2'")

Unable to determine if iframe or window in youtube export page (Selenium Python)

I am trying to create an automation wherein I can export a report from the Analytics tab from Studio.Youtube.
When I get to the page where I need to click the export button, nothing happens and it does not export the csv file. I have tried switching frames and windows but nothing happens.
Here is a sample of my code
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
driver = webdriver.Chrome(ChromeDriverManager().install())
urlYoutube = "https://studio.youtube.com/"
urlStack = "https://stackoverflow.com/users/login?ssrc=head&returnurl=https%3a%2f%2fstackoverflow.com%2f"
username = "sample#gmail.com"
password = "samplepassword"
driver.get(urlStack)
googleButtonStack = driver.find_element_by_xpath('//*[#id="openid-buttons"]/button[1]')
googleButtonStack.click()
userNameField = driver.find_element_by_xpath('//*[#id="identifierId"]')
userNameField.send_keys(username)
userNameNext = driver.find_element_by_xpath('//*[#id="identifierNext"]/div/button/div[2]')
userNameNext.click()
driver.implicitly_wait(10)
passField = driver.find_element_by_xpath('//*[#id="password"]/div[1]/div/div[1]/input')
passField.send_keys(password)
passFieldNext = driver.find_element_by_xpath('//*[#id="passwordNext"]/div/button/div[2]')
passFieldNext.click()
driver.implicitly_wait(15)
driver.get(urlYoutube)
driver.implicitly_wait(15)
analyticsButton = driver.find_element_by_xpath('//*[#id="menu-paper-icon-item-3"]')
analyticsButton.click()
driver.implicitly_wait(5)
# beforeWidnow = driver.current_window_handles
# print(beforeWidnow)
seeMoreButton = driver.find_element_by_xpath('//*[#id="see-more-button"]/div')
seeMoreButton.click()
driver.implicitly_wait(10)
# newWindow = driver.current_window_handles
# print(newWindow)
driver.switch_to.window(driver.find_element_by_xpath('/html/body/yta-explore-dialog/div'))
driver.implicitly_wait(5)
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, '//*[#id="export-button"]/iron-icon')))
driver.find_element_by_xpath('//*[#id="export-button"]/iron-icon').click()
# WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, '//*[#id="text-item-1"]/ytcp-ve/div/div/yt-formatted-string'))).click()
Is there a way to click the export button and the options in it?
I've tried your code by my own and it is working skipping the line
driver.switch_to.window(driver.find_element_by_xpath('/html/body/yta-explore-dialog/div'))
It is working fine even if you don't switch the frame.
If you want to export the csv you have to take the menu option
csv_option = driver.find_element_by_xpath("//yt-formatted-string[contains(., 'Comma-separated values (.csv)')]")
and then click it
csv_option.click()

Script fails to keep clicking on load more button

I've written a script in Python in association with selenium to keep clicking on MORE button to load more items until there are no new items left to load from a webpage. However, my below script can click once on that MORE button available on the bottom of that page.
Link to that site
This is my try so far:
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
link = "https://angel.co/companies?company_types[]=Startup&company_types[]=Private+Company&company_types[]=Mobile+App&locations[]=1688-United+States"
driver = webdriver.Chrome()
wait = WebDriverWait(driver, 10)
driver.get(link)
while True:
for elems in wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR,".results .name a.startup-link"))):
print(elems.get_attribute("href"))
try:
loadmore = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR,"[class='more']")))
driver.execute_script("arguments[0].scrollIntoView();", loadmore)
loadmore.click()
except Exception:break
driver.quit()
How can I keep clicking on that MORE button until there are no such button left to click and parse the links as I've already tried using for loop.
I've managed to solve the problem pursuing sir Andersson's logic within my exising script. This is what the modified script look like.
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
link = "https://angel.co/companies?company_types[]=Startup&company_types[]=Private+Company&company_types[]=Mobile+App&locations[]=1688-United+States"
driver = webdriver.Chrome()
wait = WebDriverWait(driver, 10)
driver.get(link)
while True:
try:
loadmore = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR,"[class='more']")))
driver.execute_script("arguments[0].click();", loadmore)
wait.until(EC.staleness_of(loadmore))
except Exception:break
for elems in wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR,".results .name a.startup-link"))):
print(elems.get_attribute("href"))
driver.quit()
why not just?
while (driver.FindElements(By.ClassName("more")).Count > 0)
{
driver.FindElement(By.ClassName("more")).Click();
//Some delay to wait lazyload to complete
}
c# example. pretty sure that it can be done with python as well

Python selenium to select first element from the dropdown list

The below piece of code clicks the file menu on a page which contain excel worksheet.
from selenium import webdriver
driver = webdriver.PhantomJS()
driver.set_window_size(1120, 550)
driver.get(r"foo%20Data%20235.xlsx&DefaultItemOpen=3") # dummy link
driver.find_element_by_css_selector('#jewel-button-middle > span').click() # responsible for clicking the file menu
driver.quit()
And I don't know how to click the first option ie, Download a snapshot option from the popup menu. I can't able to inspect the elements of pop up or dropdown menu. I want the xlsx file to get downloaded.
The idea is to load the page with PhantomJS, wait for the contents of the workbook to load, get all the necessary parameters for the download file handler endpoint request which we can do with requests package.
Full working solution:
import json
import requests
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
WORKBOOK_TYPE = "PublishedItemsSnapshot"
driver = webdriver.PhantomJS()
driver.maximize_window()
driver.get('http://www.cbe.org.eg/en/EconomicResearch/Publications/_layouts/xlviewer.aspx?id=/MonthlyStatisticaclBulletinDL/External%20Sector%20Data%20235.xlsx&DefaultItemOpen=1#')
wait = WebDriverWait(driver, 10)
wait.until(EC.presence_of_element_located((By.ID, "ctl00_PlaceHolderMain_m_excelWebRenderer_ewaCtl_rowHeadersDiv")))
# get workbook uri
hidden_input = wait.until(EC.presence_of_element_located((By.ID, "ctl00_PlaceHolderMain_m_excelWebRenderer_ewaCtl_m_workbookContextJson")))
workbook_uri = json.loads(hidden_input.get_attribute('value'))['EncryptedWorkbookUri']
# get session id
session_id = driver.find_element_by_id("ctl00_PlaceHolderMain_m_excelWebRenderer_ewaCtl_m_workbookId").get_attribute("value")
# get workbook filename
workbook_filename = driver.find_element_by_xpath("//h2[contains(#class, 's4-mini-header')]/span[contains(., '.xlsx')]").text
driver.close()
print("Downloading workbook '%s'..." % workbook_filename)
response = requests.get("http://www.cbe.org.eg/en/EconomicResearch/Publications/_layouts/XlFileHandler.aspx", params={
'id': workbook_uri,
'sessionId': session_id,
'workbookFileName': workbook_filename,
'workbookType': WORKBOOK_TYPE
})
with open(workbook_filename, 'wb') as f:
for chunk in response.iter_content(chunk_size=1024):
if chunk: # filter out keep-alive new chunks
f.write(chunk)
It easier to inspect such elements (closing dropdowns) using FireFox, open the developer tools and just stand on the element with the mouse cruiser after selecting the option from FireBug toolbar (marked in red square in the picture).
As for the question, the locator you are looking for is ('[id*="DownloadSnapshot"] > span')
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.PhantomJS()
driver.set_window_size(1120, 550)
driver.get(r"foo%20Data%20235.xlsx&DefaultItemOpen=3") # dummy link
wait = WebDriverWait(driver, 10)
wait.until(EC.invisibility_of_element_located((By.CSS_SELECTOR, '[id*="loadingTitleText"]')))
driver.find_element_by_css_selector('#jewel-button-middle > span').click() # responsible for clicking the file menu
download = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, '[id*="DownloadSnapshot"] > span')))
driver.get_screenshot_as_file('fileName')
download.click()
I observed the till the excel is completely loaded, File menu is not showing any options. So added wait till the excel book is loaded.
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
from time import sleep
from selenium.webdriver.common.action_chains import ActionChains
browser = webdriver.PhantomJS()
browser.maximize_window()
browser.get('http://www.cbe.org.eg/en/EconomicResearch/Publications/_layouts/xlviewer.aspx?id=/MonthlyStatisticaclBulletinDL/External%20Sector%20Data%20235.xlsx&DefaultItemOpen=1#')
wait = WebDriverWait(browser, 10)
element = wait.until(EC.visibility_of_element_located((By.XPATH, "//td[#data-range='B59']")))
element = wait.until(EC.element_to_be_clickable((By.ID, 'jewel-button-middle')))
element.click()
eleDownload = wait.until(EC.element_to_be_clickable((By.XPATH,"//span[text()='Download a Snapshot']")))
eleDownload.click()
sleep(5)
browser.quit()
find the element by id/tag, inspect options in a loop, select the one you want then do the click.

Categories

Resources