I want to select a radio button with selenium in python. I have tested with 3 solutions. Unfortunately it doesn't work at all. Could you do me a favor and help me. I am totally beginner.
The URL:
https://biruni.tuik.gov.tr/disticaretapp/menu_ing.zul
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
from selenium.webdriver.support.ui import Select
driver = webdriver.Chrome('C:\Webdriver\chromedriver.exe')
driver.get('https://biruni.tuik.gov.tr/disticaretapp/menu_ing.zul')
time.sleep(2)
driver.maximize_window()
element = driver.find_element(by=By.XPATH,value='//*[contains(text(), "Product/Product Groups-Partner Country")]')
element.click()
time.sleep(4)
# radio = driver.find_element_by_id("o1BQ41-real")
# radio.click()
# l=driver.find_element_by_xpath('//*[#id="o1BQ41-real"]')
# l.click()
# driver.find_element_by_css_selector("input#o1BQ41-real").click()
time.sleep(10)
You can use the same select by text to click on the radio button.
radio_element = driver.find_element(by=By.XPATH,value='//*[contains(text(), "Product/Partner Country")]')
radio_element.click()
This selects the desired element
or you can also select the element by id
radio_element = driver.find_element(by=By.XPATH,value='//span[#id="bKFP41"]')
radio_element.click()
That should solve your problem:
element = driver.find_element(by=By.XPATH,value='//html/body/div/div/div/table/tbody/tr/td/table/tbody/tr[3]/td/div/div/table/tbody[1]/tr[13]/td/div/span/span[2]/input')
element.click()
You can't use the element id in XPATH because every refresh the site changes the element id!
Related
I cannot select a select option using below Python code..
I have tried to refer many Q&A such as select, execute_script... but they are still not working.
enter image description here
import time
from selenium import webdriver
browser = webdriver.Chrome()
seoul_url = 'http://kras.seoul.go.kr/land_info/info/landprice/landprice.do'
browser.get(seoul_url)
time.sleep(1)
browser.find_element_by_xpath('//*[#id="sggnm"]/option[11]').click()
You have first click on dropdown and then click on the value that you wanted to select like below
Import
import org.openqa.selenium.JavascriptExecutor
import org.openqa.selenium.WebElement
select the desire value
WebElement element = browser.find_element_by_xpath("//option[contains(text(),'동대문구')]"); // you can choose the value you want
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", element);
My guess would be you cannot click the element as it is not visible.
To make it visible you must click the dropdown menu first as suggested by #Akzy
driver = webdriver.Chrome()
url: str = "http://kras.seoul.go.kr/land_info/info/landprice/landprice.do"
driver.get(url)
dropdown_element = driver.find_element_by_id("sggnm")
# Open the dropdown menu first
dropdown_element.click()
option_element = driver.find_element_by_xpath('//*[#id="sggnm"]/option[11]')
# Now the options are visible we want to click the option in the list
option_element.click()
This is untested (for this page) but should work for a generic webpage.
There are other ways of doing this such as sending the down key n times to the dropdown element get the nth option element.
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
import pyautogui
driver = webdriver.Chrome()
url: str = "http://kras.gb.go.kr/land_info/info/landprice/landprice.do"
driver.get(url)
time.sleep(1)
def option_click(city):
driver.find_element(By.CSS_SELECTOR, city).click()
time.sleep(1)
def option_select(pos):
i = 0
for i in range(pos):
pyautogui.press("down")
i += 1
pyautogui.press("enter")
time.sleep(1)
option_click('#sggnm')
option_select(10)
option_click('#umdnm')
option_select(3)
NEW
Or you can use ActionChains. In the code pos is the position of the option you want to select
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
import time
actions = ActionChains(driver)
def select_option(id_, pos):
driver.find_element(By.CSS_SELECTOR, id_).click()
actions.send_keys(Keys.DOWN * pos).send_keys(Keys.ENTER).perform()
select_option('#sggnm', 10)
time.sleep(1)
select_option('#umdnm', 3)
OLD
With this code you can change the currently selected option to the desired one without doing a click.
# webelement containing the currently selected option
option1 = driver.find_element(By.XPATH, '//*[#id="sggnm"]/option[1]')
# string with the text of the 11th option
option11 = driver.find_element(By.XPATH, '//*[#id="sggnm"]/option[11]').text
# replace the current option with the 11th option
driver.execute_script("var el = arguments[0]; arguments[1].innerText = el", option11, option1)
I'm stuck with a dropdown that I can't get pass in Selenium.
I'm trying to collect some price data using Selenium from this link:
https://xxx. In this link, you need to click on a button (Next), then select any option in the subsequent dropdown, then press (Next) again to advance into the information page that I wanted to collect some information. I'm stuck at the dropdown - I am unable to select any option.
This is my code thus far:
browser.get("https://xxx/#/pricePlans/step1")
wait = WebDriverWait(browser, 10)
while True:
try:
button = browser.find_element_by_css_selector('body > div.md-dialog-container.ng-scope > md-dialog > md-dialog-actions > div > button')
except TimeoutException:
break
button.click()
options_box= browser.find_element_by_class_name('bullet-content-title')
wait = WebDriverWait(browser, 5)
options_box.click()
The issue lies with the dropdown options (It has options like HDB 1-room, HDB 2-room etc). I tried to reference the option box by XPATH, CSS selector, class_name (as seen above) but with the snippet above, Spyder issues time-out. Other snippets I tried included:
ui.WebDriverWait(browser, 10).until(EC.element_to_be_clickable((By.CLASS_NAME, "bullet-content-title")))
using XPATH, class_name but no luck.
I'm a newbie at web scraping who got thus far by searching the SO, but I am unable to find much solutions regarding (md-select) dropdowns.
I also attempted to use
ActionChains(driver).move_to_element(options_box).click(options_box)
but I did not see any clicking nor mouse movements so i'm stumped.
I appreciate any advice at this point of time. Thank you so much!
Edit:
Code Snippets and Responses:
from selenium import webdriver
from selenium.webdriver.support import ui
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 TimeoutException
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.action_chains import ActionChains
option = webdriver.ChromeOptions()
option.add_argument('--incognito')
browser = webdriver.Chrome(executable_path='C:\\ChromeDriver\\chromedriver.exe', options=option)
browser.get("https://xxx")
wait = WebDriverWait(browser, 10)
while True:
try:
button = browser.find_element_by_css_selector('body > div.md-dialog-container.ng-scope > md-dialog > md-dialog-actions > div > button')
except TimeoutException:
break
button.click()
options_box = browser.find_element_by_class_name('bullet-content-title')
wait = WebDriverWait(browser, 5)
options_box.click()
This returns "StaleElementReferenceException: stale element reference: element is not attached to the page document"
Which I assume it is due to the presence of the second "Next" Button which is inert at the moment.
options_box = ui.WebDriverWait(browser, 10).until(EC.element_to_be_clickable((By.CLASS_NAME, "bullet-content-title")))
options_box.click()
Does nothing. Spyder eventually returned me TimeOut Error.
#AndrewRay answer is good for getting the value but not for selecting the options. you can do this to select the options.
#browser.get("https://......")
wait = WebDriverWait(browser, 10)
try:
browser.find_element_by_css_selector('button.green-btn').click()
# wait until dialog dissapear
wait.until(EC.invisibility_of_element_located((By.CSS_SELECTOR, 'md-dialog[aria-describedby="dialogContent_0"]')))
# click the dropdown
browser.find_element_by_css_selector('md-input-container').click()
# select the option element
setOptionElement = browser.find_element_by_css_selector('md-option[value="HDB Executive"]')
# need to scrollIntoView if the option in the bottom
# or you get error the element not clickable
browser.execute_script('arguments[0].scrollIntoView();arguments[0].click()', setOptionElement)
except Exception as ex:
print(ex)
driver.get('https://compare.openelectricitymarket.sg/#/pricePlans/step1')
time.sleep(5)
next_btn = driver.find_element_by_css_selector('button.green-btn')
next_btn.click()
dropdown = driver.find_element_by_id('select_4')
options = dropdown.find_elements_by_tag_name('md-option')
for option in options:
print option.get_attribute('value')
Hope this helps. Use the .get_attribute method to find the value of the option and click that option if matches the desired value. :)
I am trying to click on a link and can't seem to get it to work. I click all the way up to the page I need, but then it won't click the last link. The code is as follows:
from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.keys import Keys
import time
from bs4 import BeautifulSoup
import requests
import pandas as pd
import openpyxl
from password import DKpassword
#import SendKeys
beginningTime = time.time()
browser = webdriver.Chrome()
browser.get('https://www.draftkings.com/lobby')
browser.maximize_window()
time.sleep(5)
signinLink = browser.find_element_by_xpath("""//*[#id="react-mobile-home"]/section/section[2]/div[2]/div[3]/div/input""")
signinLink.click()
signinLink.send_keys("abcdefg")
signinLink.send_keys(Keys.TAB)
passwordLink = browser.find_element_by_xpath("""//*[#id="react-mobile-home"]/section/section[2]/div[2]/div[4]/div/input""")
passwordLink.send_keys(DKpassword)
passwordLink.send_keys(Keys.ENTER)
time.sleep(5)
if browser.current_url == "https://www.draftkings.com/account/sitelogin/false?returnurl=%2Flobby1":
signin = browser.find_element_by_partial_link_text("SIGN IN")
signin.click()
elif browser.current_url == "https://www.draftkings.com/lobby#/featured":
mlbLink = browser.find_element_by_partial_link_text("MLB")
mlbLink.click()
else:
print("error")
time.sleep(5)
featuredGame = browser.find_element_by_class_name("GameSetTile_tag")
featuredGame.click()
time.sleep(5)
firstContest = browser.find_element_by_partial_link_text("Enter")
firstContest.click()
I receive the error message that the element is not clickable at point... and another element would receive the click. Any help would be greatly appreciated. I don't care which contest is clicked on as long as it is on the featured page which the previous code directs it too.
There can be multiple reasons for that.
1. You might have to scroll down or might have to perform some action so that it'll be visible to script.
for scroll down you can use this code :
browser.execute_script("window.scrollTo(0, Y)")
where Y is the height (on a fullhd monitor it's 1080)
2. There can be multiple web element present , in this case you have to use unique element from dom , you can check that by right click > inspect > under element section > CTRL+F > write your locator (in your case xpath) to check how many entries are present.
You can try with this xpath also :
//a[contains(text(),'Enter') and contains(#href,'/contest/draftteam') and contains(#class,'dk-btn-dark')]
Code :
WebDriverWait(driver, 20).until(
EC.element_to_be_clickable((By.XPATH, "//a[contains(text(),'Enter') and contains(#href,'/contest/draftteam') and contains(#class,'dk-btn-dark')]"))
firstContest = browser.find_element_by_xpath("//a[contains(text(),'Enter') and contains(#href,'/contest/draftteam') and contains(#class,'dk-btn-dark')]")
firstContest.click()
Replace click event with action class, which will solve this Exception
from selenium.webdriver.common.action_chains import ActionChains
actions = ActionChains(driver)
actions.move_to_element(firstContest).click().perform()
I was able to overcome this exception by using Click through JavaScript executor instead of regular Element.click(), as below-
WebElement element = webDriver.findElement(By.xpath(webElemXpath));
try {
JavascriptExecutor ex = (JavascriptExecutor) webDriver;
ex.executeScript("arguments[0].click();", element);
logger.info(elementName was + " clicked");
}
catch (NoSuchElementException | TimeoutException e) {
logger.error(e.getMessage());
}
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from bs4 import BeautifulSoup
import time
url = "https://www.bungol.ca/"
driver = webdriver.Firefox(executable_path ='/usr/local/bin/geckodriver')
driver.get(url)
#myElem = WebDriverWait(browser, delay).until(EC.presence_of_element_located((By.ID, 'IdOfMyElement')))
searchbutt = """/html/body/section/div[2]/div/div[1]/form/div/button""" #click search to get to map
active_listing = """//*[#id="activeListings"]"""
search_wait = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, searchbutt)))
search_wait.click()
active_wait = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, active_listing)))
active_wait.click()
driver.find_element_by_xpath("""//*[#id="useDateRange"]""").click() #use data range
time.sleep(1)
driver.find_element_by_xpath("""//*[#id="dateRangeStart"]""").click() #start range
time.sleep(1)
month_path = driver.find_element_by_xpath("""/html/body/div[17]/div/div/div[1]/select""") #click the month to bring combo box list option
driver.execute_script("arguments[0].click();", month_path)
I am trying to select January 1, 2015 on this calendar which requires you to click:
https://www.bungol.ca/map/?
use date range (no problem doing this)
click the start range (no problem)
click the month which brings up a combo form of options (can't click)
click year - can't click
click the date - can't click
I tried:
locate the element by xpath and css path but neither method works.
move_to_element method but still doesn't work
switch to frame method - doesn't work because it's not inside an iframe
use javascript to click it found here: How do you click on an element which is hidden using Selenium WebDriver?
scroll to element - doesn't do anything because element is already on screen
Here is a code block to solve your issue, I reorganized some of your code as well. Please make sure to import this from selenium.webdriver.support.ui import Select so you can use the Select in the code block:
driver.get('https://www.bungol.ca/')
wait = WebDriverWait(driver, 10)
wait.until(EC.element_to_be_clickable((By.XPATH, './/button[#type="submit" and text()="Search"]'))).click()
wait.until(EC.element_to_be_clickable((By.ID, 'activeListings'))).click()
wait.until(EC.element_to_be_clickable((By.ID, 'useDateRange'))).click()
# I found that I had to click the start date every time I wanted to interact with
# anything related to the date selection div/table
wait.until(EC.element_to_be_clickable((By.XPATH, './/input[#id="dateRangeStart" and #name="soldDateStart"]')))
driver.find_element_by_xpath('.//input[#id="dateRangeStart" and #name="soldDateStart"]').click()
yearSelect = Select(driver.find_element_by_xpath('.//select[#class="pika-select pika-select-year"]'))
yearSelect.select_by_visible_text('2015')
wait.until(EC.element_to_be_clickable((By.XPATH, './/input[#id="dateRangeStart" and #name="soldDateStart"]')))
driver.find_element_by_xpath('.//input[#id="dateRangeStart" and #name="soldDateStart"]').click()
monthSelect = Select(driver.find_element_by_xpath('.//select[#class="pika-select pika-select-month"]'))
monthSelect.select_by_visible_text('January')
wait.until(EC.element_to_be_clickable((By.XPATH, './/input[#id="dateRangeStart" and #name="soldDateStart"]')))
driver.find_element_by_xpath('.//input[#id="dateRangeStart" and #name="soldDateStart"]').click()
driver.find_element_by_xpath('.//td[#data-day="1"]').click()
After running that, you should have the date selected January 1, 2015 for the first part of the range. You can use the same techniques to select the second part of the range if needed.
For more information on how to use the Select please visit THIS.
I'm trying to automate the search process in this website: https://www.bcbsga.com/health-insurance/provider-directory/searchcriteria
The process involves clicking on the "Continue" button to search under the 'guest' mode. The next page has got a list of drop-down items to refine the search criteria. My code either produces the "Element not visible" exception (which I corrected by using a wait) or times out. Please help.
Here's my code:
# navigate to the desired page
driver.get("https://www.bcbsga.com/health-insurance/provider-directory/searchcriteria")
# get the guest button
btnGuest = driver.find_element_by_id("btnGuestContinue")
#click the guest button
btnGuest.click()
wait = WebDriverWait(driver,10)
#Find a Doctor Search Criteria page
element = wait.until(EC.visibility_of_element_located((By.ID,"ctl00_MainContent_maincontent_PFPlanQuestionnaire_ddlQuestionnaireInsurance")))
lstGetInsurance = Select(element)
lstGetInsurance.select_by_value("BuyMyself$14States")
# close the browser window
#driver.quit()
you can use input search and key.return:
import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
divID = 'ctl00_MainContent_maincontent_PFPlanQuestionnaire_ddlQuestionnaireInsurance_chosen'
inputID = 'ctl00_MainContent_maincontent_PFPlanQuestionnaire_ddlQuestionnaireInsurance_chosen_input'
inputValue = 'I buy it myself (or plan to buy it myself)'
driver = webdriver.Chrome()
driver.get("https://www.bcbsga.com/health-insurance/provider-directory/searchcriteria")
driver.find_element_by_id("btnGuestContinue").click()
driver.implicitly_wait(10)
driver.find_element_by_id(divID).click()
driver.find_element_by_id(inputID).send_keys(inputValue)
driver.find_element_by_id(inputID).send_keys(Keys.RETURN)
time.sleep(6)
driver.close()