Python + Selenium JS dropdown select - python

I'm totally new, I've gone through some of the examples as you can find these here but as straightforward as it looks I can't make it work.
The page I want to pass: www.webauto.de
My code to select a make, a model and click 'search'.
browser = webdriver.Firefox()
browser.get('http://www.webauto.de')
WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.ID, 'quick-search')))
select = Select(browser.find_element_by_id('carsearchmake'))
select.select_by_visible_text('Ford')
sleep(1)
select = Select(browser.find_element_by_id('carsearchmod'))
select.select_by_visible_text('Fiesta')
browser.find_element_by_xpath('//input[#type="submit"]').click()
sleep(1)

I used the an attribute = value CSS selector to target the submit button.
from selenium import webdriver
d = webdriver.FireFox()
d.get("https://www.webauto.de/")
d.find_element_by_xpath("//select[#id='carsearchmake']/option[text()='Ford']").click()
d.find_element_by_xpath("//select[#id='carsearchmod']/option[text()='Fiesta']").click()
d.find_element_by_css_selector("[value=Suchen]").click()
#d.quit()

Seems you were pretty close.
The xpath:
browser.find_element_by_xpath('//input[#type="submit"]')
doesn't identifies the desired search button uniquely and you can use the following solution:
browser.find_element_by_xpath("//a[#href='https://www.webauto.de/site/de/suchen/' and contains(.,'Erweiterte Suche')]//following::a[1]/input").click()

Related

How to click radio button with selenium in python?

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!

Changing attribute values of a tag using selenium python

I want to click on Select Year dropdown and select a year from it. Go to that page and fetch the HTML.
I've written this piece of code:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome('C:/Users/SoumyaPandey/Desktop/Galytix/Scrapers/data_ingestion/chromedriver.exe')
driver.get('https://investors.aercap.com/results-and-events/financial-results')
driver.maximize_window()
driver.find_element_by_id('year_filter_chosen').click()
driver.find_element_by_class_name('active-result')
I'm just starting to work with selenium and got no clue how to proceed further.
I tried to look for the next class after clicking on the dropdown. I want to set the attribute value 'data-option-array-index' to 1 first, open the page, get html. Then keep on changing the value of this attribute.
Any help would be much appreciated!!
driver.get('https://investors.aercap.com/results-and-events/financial-results')
elem=driver.find_element_by_css_selector('#year-filter')
driver.execute_script("arguments[0].style.display = 'block';", elem)
selectYear=Select(elem)
selectYear.select_by_index(1)
Simply find the element and use Select after you change it's style to display block to access it's values.
Imports
from selenium.webdriver.support.select import Select
For tag in selenium there's great Class Select, example provided my colleague in the neighbor answer. But there's also a bit easier way to do it as well, like:
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
driver.get('https://investors.aercap.com/results-and-events/financial-results')
el = driver.find_element(By.CSS_SELECTOR, '#year-filter')
time.sleep(3)
driver.execute_script("arguments[0].style.display = 'block';", el)
el.send_keys('2018')
time.sleep(3)
driver.quit()

Button Click element issue in selenium using python

I am trying to click button(name command page) on web page but i am unable to do so. i am using selenium with python
code:
wait= WebDriverWait(driver,20)
command_page = wait.until(EC.element_to_be_clickable((By.ID,"Button_ID")))
command_page.click()
I have tried by class name also but i am unable to click the element.
Please help me on this.
As an alternative you can use JavascriptExecutor to perfrom click on certain element if Selenium click() method doesn't trigger the action without any Exception.
element = driver.find_element_by_id("etoolbar_toolbarSection_newcommandpagebtn_id")
driver.execute_script("arguments[0].click();", element)
Please try below solution :
WebDriverWait(driver, 20)
both_button=wait.until(EC.element_to_be_clickable((By.XPATH, "//*[contains(text(), 'Command Page')]")))
both_button.click()
I tried this, seems to be working
from selenium import webdriver
driver = webdriver.Firefox()
driver.get("file://c:/cygwin64/home/das2/abcd.html")
element = driver.find_element_by_id("etoolbar_toolbarSection_newcommandpagebtn_id")
element.click()

Click and view more pages with Selenium in Python

Problem
I need to go into all the top user profile in this page using Selenium.
The Top users profile are located in the right of the page.
What i've done
self.driver.get(response.url)
user_list = self.driver.find_elements_by_xpath('//table[contains(#class,"W-100 Bc-c")]/tbody/tr')
for single_user in user_list:
single_user.find_element_by_xpath('.//td/a').click()
time.sleep(3)
But I get this error message:
WebDriverException: Message: unknown error: Element is not clickable
at point (865, 685). Other element would receive the click:
<div id="MouseoverMask" class="End-0 Start-0 T-0 B-0"></div>
Info
Python 2.7.10
Selenium 2.48
Pycharm
EDIT+
I try to make a print of the name and it works:
print(str( single_user.find_element_by_xpath('.//td/a').text ) )
But the click() no.
if you sure that the object you get is the right one, often the problem is:
The object is not visible
Page was not fully loaded when you try to click on the object.
So just take a look on the Wait method provided by Selenium and be sure your object is visible
In order to wait an element to be clickable :
from selenium.webdriver.support import expected_conditions as EC
wait = WebDriverWait(driver, 10)
element = wait.until(EC.element_to_be_clickable((By.ID,'someid')))
In your case, you can try to find each element with the id you got and click on it :
self.driver.get(response.url)
user_list = self.driver.find_elements_by_xpath('//table[contains(#class,"W-100 Bc-c")]/tbody/tr')
for single_user in user_list:
id = single_user.find_element_by_xpath('.//td/a').get_attribute("id")
self.driver.find_elements_by_id(id).click()
time.sleep(3)
I don't see any error at my end but after first click web elements are changed so you will not get the next web element as captured earlier in xpath. By the way try below code-
from selenium import webdriver
import time
driver = webdriver.Firefox()
driver.get('https://answers.yahoo.com/dir/index/discover?sid=396545663')
user_list = driver.find_elements_by_xpath('//table[contains(#class,"W-100 Bc-c")]/tbody/tr')
lnks = [i.find_element_by_xpath('.//td/a').get_attribute('href') for i in user_list]
for single_user in lnks:
driver.get(single_user)
time.sleep(3)

Selenium Element not visible exception

I have been tasked with writing a parser to click a button on a website and I am having issues to click only one of the buttons. The following code works on every button except one.
Here's the html:
http://pastebin.com/6dLF5ru8
here's the source html:
http://pastebin.com/XhsedGLb
python code:
driver = webdriver.Firefox()
...
el = driver.find_element_by_id("-spel-nba")
actions.move_to_element(el)
actions.sleep(.1)
actions.click()
actions.perform()
I am getting this error.
ElementNotVisibleException: Message: Element is not currently visible and so may not be interacted with
as per Saifur I just tried waits with the same element not visible exception:
wait = WebDriverWait(driver, 10)
wait.until(EC.presence_of_element_located((By.XPATH, "//input[contains(#id,'spsel')][#value='nba']"))).click()
If you look at the page source, you'll understand that almost all of theSELECT, DIV elements are faked and created from JavaScript, that is why webdriver cannot SEE them.
There's a workaround though, by using ActionChains to open your developer console, and inject an artificial CLICK on the desired element, which in fact, is the Label triggering the NBA data loading... here's a working example:
from selenium import webdriver
from selenium.webdriver.common import action_chains, keys
import time
driver = webdriver.Firefox()
driver.get('Your URL here...')
assert 'NBA' in driver.page_source
action = action_chains.ActionChains(driver)
# open up the developer console, mine on MAC, yours may be diff key combo
action.send_keys(keys.Keys.COMMAND+keys.Keys.ALT+'i')
action.perform()
time.sleep(3)
# this below ENTER is to rid of the above "i"
action.send_keys(keys.Keys.ENTER)
# inject the JavaScript...
action.send_keys("document.querySelectorAll('label.boxed')[1].click()"+keys.Keys.ENTER)
action.perform()
Alternatively to replace all the ActionChains commands, you can simply run execute_script like this:
driver.execute_script("document.querySelectorAll('label.boxed')[1].click()")
There you go, at least on my local file anyway... Hope this helps!
What worked for me was to find the element just before the problematic one (that is, just before it in terms of tab order), then call Tab on that element.
from selenium.webdriver.common.keys import Keys
elem = br.find_element_by_name("username")
elem.send_keys(Keys.TAB) # tab over to not-visible element
After doing that, I was able to send actions to the element.
The actual solution of this thread did not work for me.
however,
this one did :
element = WebDriverWait(driver, 3).until(EC.visibility_of_element_located((By.XPATH, xpaths['your_xpath_path'])))
the trick is to use :
EC.visibility_of_element_located
the WebDriverWait
WebDriverWait
from this import :
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
I suggest you use xpath with explicit wait
//input[contains(#id,'spsel')][#value='nba']
if "Element is not currently visible" then make it VISIBLE
f.e.
>>> before is hidden top is outside of page
<input type="file" style="position: absolute;top:-999999" name="file_u">
>>> after move top on in page area
DRIVER.execute_script("document.getElementByName('file_u').style.top = 0;")
time.sleep(1); # give some time to render
DRIVER.find_element_by_name("file_u").send_keys("/tmp/img.png")
Instead of get_element_by_id() you can try elem = browser.find_element_by_css_selector('#elemId') (go to that webpage and the element, right click it and Copy CSS Selector, or something like that.) This is what i did and it works. You also try find_element_by_link_text(text), find_element_by_partial_link_text(text), find_element_by_tag_name(tagName_case_insensitive_here), find_element_by_name(name) etc. Something will work. After the id the CSS Selector is your best bet.
I ended up using #twasbrillig's solution, but instead of finding the previous element and sending a TAB keypress, I find the desired element, send a TAB keypress with that element, and then a SHIFT + TAB keypress to the driver:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Firefox()
el = driver.find_element_by_id("-spel-nba")
el.send_keys(Keys.TAB)
webdriver.ActionChains(driver).key_down(Keys.SHIFT).send_keys(Keys.TAB).key_up(Keys.SHIFT)
I tried using the other methods but in the end found that the simplest way was to just try and click the button, and catch the error. This allows me to perform other actions based on if it worked (True) or didn't (False).
def click_button(html_object):
try:
html_object.click()
except:
return False #most likely because it is NotVisible object and can be ignored
return True
...
...
click_button(actions)
The way I solved this in python was:
try:
# the element you want to scroll to
element = driver.find_element_by_id("some_id")
ActionChains(driver).move_to_element(element).perform()
element.send_keys(Keys.TAB).key_up(Keys.SHIFT)
#element.click()
except Exception as e:
print(e)

Categories

Resources