I want to get selected option using Selenium WebDriver with Python
but I used select_by_value can't get vaule
I have the following HTML code
<select id="play_date" name="play_date" onclick="javascript:GoodsInfo.GetPlayDate(this);" onmouseover="javascript:GoodsInfo.GetPlayDate(this);" onchange="javascript:GoodsInfo.GetPlayTime(this.value);">
<option value="" selected="">Select Date</option>
<option value="20230202" style="color: black;">Thu, Feb 02, 2023</option></select>
I am trying to get a list of the option values ('20230202') using Selenium.
At the moment I have the following Python code
select_date = Select(wait.until(EC.element_to_be_clickable((By.XPATH, "//*[#id='play_date']"))))
select_date.select_by_value('20230202')
but it's always have is
selenium.common.exceptions.NoSuchElementException: Message: Could not locate element with index 1
Any help or pointers is appreciated, thank you!
If you get error NoSuchElementException it means that you are using a wrong xpath/css_selector or that the element is inside an iframe. You can check by looking at the HTML
So your case is the latter, and to make the xpath work you have first to switch to the iframe, using driver.switch_to.frame() or better EC.frame_to_be_available_and_switch_to_it.
WebDriverWait(driver, 9).until(EC.frame_to_be_available_and_switch_to_it((By.ID, "product_detail_area")))
dropdown_date = WebDriverWait(driver,9).until(EC.element_to_be_clickable((By.ID, "play_date")))
options = []
# open menu so that options are loaded
dropdown_date.click()
# wait until options are loaded
while not options:
options = driver.find_elements(By.CSS_SELECTOR, "#play_date option:not([value=''])")
time.sleep(1)
# close menu
dropdown_date.click()
print('available options:')
for opt in options:
print(opt.get_attribute('value'))
select_date = Select(dropdown_date)
select_date.select_by_value(input('enter value: '))
Related
I'm trying to select an element from a dropdown but getting an error.
Here is the HTML:
<select id="childContextDDL" data-filter="contains" data-role="dropdownlist" data-template="dcf-context-picker" data-value-field="Value" data-text-field="DisplayText" data-bind="events: { change: childContextListChange }, source: childContextList.ChildContextList" style="display: none;">
<option value="1">NATION</option>
<option value="12">ATLANTIC</option>
<option value="16">CHARLOTTE, NC</option>
And this is the code that I'm trying to run:
mySelect = Select(driver.find_element_by_id("childContextDDL"))
print('MySelect is: ',mySelect)
mySelect.select_by_visible_text('ATLANTIC')
I'm getting this error:
selenium.common.exceptions.ElementNotInteractableException: Message: element not interactable: Element is not currently visible and may not be manipulated
What's the possible reason for getting this error? I'm very new to Selenium.
I also want to click on that element after selecting it.
The problem was that the style within the html was set to none. So I had to first change that style to block to make it visible and then proceed with the clicking operation.
Here's the code that worked:
driver.execute_script("document.getElementById('childContextDDL').style.display = 'block';")
mySelect = Select(driver.find_element_by_id("childContextDDL"))
print('MySelect is: ',mySelect)
mySelect.select_by_visible_text('ATLANTIC')
randomClick = driver.find_element_by_id('dcf-user-info')
randomClick.click()
I guess the mySelect element (the dropdown menu) is not visible.
So please try the following:
from selenium.webdriver.common.action_chains import ActionChains
actions = ActionChains(driver)
mySelect = Select(driver.find_element_by_id("childContextDDL"))
actions.move_to_element(mySelect).perform()
mySelect.select_by_visible_text('ATLANTIC')
If the above doesn't work (I can't see the actual site you are working on), the following can work instead in the element has to be tapped to become enabled
action = TouchActions(driver)
action.tap(mySelect).perform()
mySelect.select_by_visible_text('ATLANTIC')
If it says it is not currently visible, you should try pausing the code with one of this options:
time.sleep(1) #This states to your code to stop for 1 second and the continue with the work.
WebDriverWait(driver, 10).until(EC.element_to_be_visible(BY.value, "12")) # tells the driver to wait a maximum of ten seconds until the value "12" is visible for the driver.
quick preface: I'm new to python and scraping so it's possible that I'm making an extremely obvious mistake.
I am trying to use Selenium to automate a few processes, the first of which is to open https://shop.anyseals.com/index.phtml and enter in a username and password.
This is how I am approaching it - A method that has worked for me without issue in the past with other websites.
from selenium import webdriver
import time
chromedriver = "A:\Downloads\chromedriver_win32 (1)/chromedriver"
driver = webdriver.Chrome(chromedriver)
driver.get("https://shop.anyseals.com/index.phtml")
#Let's wait for X seconds so that the elements can load.
time.sleep(3)
user = "username#user.com"
use = driver.find_element_by_xpath('//*[#id="userkey"]')
use.send_keys(user)
I'm using the xpath from the html associated with the username input. (html shown below)
<input name="userkey" id="userkey" style="width:100%" type="text"
onkeydown="if(event.keyCode=='13')perform_login('smp');">
I keep getting the error shown below that states that there is no such element.
What am I missing here?
selenium.common.exceptions.NoSuchElementException:
Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[#id="userkey"]"}
I am not a very experienced coder so apologies if I say smth stupid.
I am using Python (in Spyder) to get Selenium to fill in a website form containing username and password. Here's the target - link.
When I lookup the "username" element by pressing F12 in a regular browser I get the following:
<input class="slds-input input" type="text" aria-describedby="" placeholder="Username" id="172:0" data-aura-rendered-by="176:0" data-interactive-lib-uid="2">
So I attempt to locate the element using the ID. However when I run the script, I get the following error in Chrome:
NoSuchElementException: no such element: Unable to locate element: {"method":"css selector","selector":"[id="172:0"]"}
Same when I run it in Firefox instead:
NoSuchElementException: Unable to locate element: [id="172:0"]
When I check HTML in the Selenium driven browser, I can see that the page code is (ie element ID) different, as below
<input class="slds-input input" type="text" aria-describedby="" placeholder="Username" id="78:2;a" data-aura-rendered-by="82:2;a" data-interactive-lib-uid="2">
My best guess is that the difference in HTML code is the reason for error. I found people posting similar issues but those were slightly different and I was not able to solve my issue using the solutions proposed there. I would appreciate is someone could help with my case.
Use xpath instead of id since it changes dynamically
Xpath for UserName: //label/following-sibling::input
Xpath for Password: //lightning-input//div//input
Sample working code which works in java convert with using above xpath in python and also add implicitlyWait and pageLoadTimeout befor launching the website
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("https://lta-tennis.force.com/"); // WebElement
driver.findElement(By.xpath("//label/following-sibling::input")).sendKeys("dummy");
driver.findElement(By.xpath("//lightning-input//div//input")).sendKeys("dummy");
System.out.println(driver.getTitle());
Edit 1: Based on OP comment
This is working xpath
try these xpaths
//input[#placeholder="Username"]
//input[#placeholder="Password"]
here is the full code
from selenium import webdriver
import time
browser = webdriver.Chrome('C:\\driverpath\\chromedriver.exe')
url = 'https://lta-tennis.force.com/s/login/'
get = browser.get(url)
time.sleep(5)
browser.find_element_by_xpath('//input[#placeholder="Username"]').send_keys('hello')
browser.find_element_by_xpath('//input[#placeholder="Password"]').send_keys('pass')
I am trying to login to beeradvocate.com to scrape (crawl) some beer data.
I tried with selenium but have been brutally failing.
here is the html
<input type="text" name="login" value="" id="ctrl_pageLogin_login" class="textCtrl" tabindex="1" autofocus="autofocus" style="background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR4nGP6zwAAAgcBApocMXEAAAAASUVORK5CYII="); cursor: auto;">
i tried using name and value and class but everything has failed.
I attempted Xpath as my final try, but have failed as well.
website and inspection
My code:
driver=webdriver.Chrome("~~~~\\chromedriver.exe")
driver.get("https://www.beeradvocate.com/community/login/")
from selenium.common.exceptions import TimeoutException
driver.maximize_window()
while True:
try:
WebDriverWait(driver, 30).until(EC.element_to_be_clickable((By.XPATH,'//*[#id="ctrl_pageLogin_login"]'))).send_keys("scentmaster")
break
except TimeoutException:
print("too much time")
I've made the button work with:
button = driver.find_element_by_xpath('//*[#id="pageLogin"]/dl[3]/dd/input')
driver.execute_script("arguments[0].click();", button)
However, I need to be able to perform sent_keys to type in id and pw to log in...
Anybody got some idea?
There are 2 fields on the page if you use xpath //*[#id = "ctrl_pageLogin_login"], the input field you are referring to is the second. Sadly, the selenium find element by default refers to the first. It will work if you make it like this: (//*[#id = "ctrl_pageLogin_login"])[2].
But I have another suggestion, try to locate element by css selector with this value : form#pageLogin input#ctrl_pageLogin_login
WebDriverWait(driver, 30).until(EC.element_to_be_clickable((By.CSS_SELECTOR,'form#pageLogin input#ctrl_pageLogin_login'))).send_keys("scentmaster")
#for password
driver.find_element_by_css_selector('form#pageLogin input#ctrl_pageLogin_password').send_keys('your_password')
#for submit
driver.find_element_by_css_selector('form#pageLogin input[type=submit]').click()
To feed the username, try this xpath:
'//form/dl/dd/input[#id="ctrl_pageLogin_login"]'
for the password:
'//form/dl/dd/input[#id="ctrl_pageLogin_password"]'
WebDriverWait(driver, 30).until(EC.element_to_be_clickable((By.CSS_SELECTOR,'form#pageLogin input#ctrl_pageLogin_login'))).send_keys("scentmaster")
#for password
driver.find_element_by_css_selector('form#pageLogin input#ctrl_pageLogin_password').send_keys('your_password')
#for submit
driver.find_element_by_css_selector('form#pageLogin input[type=submit]').click()
The solution above given by frianH worked! :)
I want to perform TAB action until I have reached a particular web-element. Until the active element is the below mentioned element, TAB action has to be performed.
>name = driver.find_element_by_name("name")
>name.send_keys("ABC")
>group = driver.find_element_by_name("group")
>group.send_keys("DEF")
I am able to find element till the above state. After that, I want to perform TAB action until the below mentioned element is found. I guess using a loop would help.
elem = driver.find_element_by_css_selector('.PeriodCell input')
Please find below the HTML code
<div class="PeriodCell" style="left:px; width:112px;">
<div class="Effort forecasting">
<div class="entity field-value-copy-selected">
<input type="text" value="0.0" data-start="2014-09-20">
</div>
</div>
<div class="Effort unmet zero" title="">0.0
</div>
</div>
Please help. Thanks in Advance.
You can bring the element to the visible part of the screen by using one of the following methods.
Using driver.execute_script("arguments[0].scrollIntoView();", element)
you can read more about scrollIntoView() method here.
Using the Actions class of selenium webdriver.
from selenium.webdriver.common.action_chains import ActionChains
element = driver.find_element_by_css_selector('.PeriodCell input')
actions = ActionChains(driver)
actions.move_to_element(element).perform()
You can read the difference between these two methods here
If you still need to use the TAB action to reach the element
from selenium.webdriver.common.keys import Keys
and using .send_keys(Keys.TAB) send the TAB key to the element
To perform TAB Action until you find a particular WebElement would not be as per the best practices. As per your comment the element is hidden so you need to bring the element within the Viewport first and then invoke click()/send_keys() as follows:
myElement = driver.find_element_by_xpath("//div[#class='PeriodCell']//input[#type='text'][#value=\"0.0\"]")
driver.execute_script("return arguments[0].scrollIntoView(true);", myElement)
# perfrom any action on the element
However the alternative using the TAB Action is as follows:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
global element
element = driver.find_element_by_name("name")
element.send_keys("ABC")
element = driver.find_element_by_name("group")
element.send_keys("DEF")
while True:
element.send_keys(Keys.TAB)
element = driver.switch_to_active_element()
if (element.get_attribute("type")=='text' and element.get_attribute("value")=='0.0' and element.get_attribute("data-start")=='2014-09-20'):
print("Element found")
break
# do anythin with the element