Apperantly none of the methods i found on stackoverflow or in the documentation worked (in FireFox webdriver only ^^°). So i made this workaround which makes a transition between the value of the option and the text of the option. The options text will then be sent as keys to select the right option in the browser, lol!
# -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import NoAlertPresentException
import unittest, time, re
import time #debugging using your eyes
from captchaUrlToText import CaptchaUrlToText
import getopt
import sys
import tracebackclass
StackSelectOptionScrape(unittest.TestCase):
def setUp(self):
#self.driver = webdriver.Firefox()
self.driver = webdriver.Chrome()
self.driver.implicitly_wait(30)
url ='http://localhost/pysel.html'#location with select/option code
self.base_url = url
self.verificationErrors = []
self.accept_next_alert = True
def test_yadda(self):
driver = self.driver
driver.get(self.base_url)
self.selectOptionByValue('//select','196277',driver)
def selectOptionByValue(self,selectElem,optionValue,driver):
"""Select an option of a drop down menu using selenium webdriver Chrome or FireFox
selecting the text that belongs to a value will always work since the options
always have a unique value and text, otherwise they would not make much sense as
options, would they? =) """
# first get the keys to send
keys = ""
element = driver.find_element_by_xpath(selectElem)
all_options = element.find_elements_by_tag_name("option")
for option in all_options:
value = option.get_attribute("value")
text = option.get_attribute("text")
print("Value is: %s" % value)
print("Text is: %s" % text)
if value == optionValue:
keys = text
# now send keys if menu is popped up
element.click() # make menu pop up
element.send_keys(keys) # send keys to select option (text)
element.click() # select option
time.sleep(3) # verify with your eyes ^^-d
def is_element_present(self, how, what):
try: self.driver.find_element(by=how, value=what)
except NoSuchElementException, e: return False
return True
def is_alert_present(self):
try: self.driver.switch_to_alert()
except NoAlertPresentException, e: return False
return True
def close_alert_and_get_its_text(self):
try:
alert = self.driver.switch_to_alert()
alert_text = alert.text
if self.accept_next_alert:
alert.accept()
else:
alert.dismiss()
return alert_text
finally: self.accept_next_alert = True
def tearDown(self):
self.driver.quit()
self.assertEqual([], self.verificationErrors)
if __name__ == "__main__":
unittest.main()
I dont know, sometimes selenium is like hell, so if you are looking for a good scraping (not webtesting) framework i recommend scrapy.org !