Reputation: 29
I am trying to input some text in a search box using selenium and python. The code is below. It runs perfectly well up until the point if selecting the 'premier league' option. Although when this text is entered it comes up in the box as a pre-defined option I am unable to select and click it as I want...If you are navigating the webpage you can click on the 'premier league' option and it loads a new page. I don't seem to be able to replicate this
import time
from selenium import webdriver
from selenium.common.exceptions import NoSuchAttributeException
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
browser = webdriver.Firefox()
browser.get("http://www.bbc.co.uk/sport/football/scores-fixtures")
try:
elem = browser.find_element_by_class_name('sp-c-date-picker-timeline__item')
except:
print('Was not able to find an element with that name.')
time.sleep(5)
elem.click()
try:
elem2=browser.find_element_by_class_name('sp-c-search__input')
except:
print('Not able to find an element with that name')
time.sleep(3)
elem2.send_keys('premier league')
time.sleep(2)
#searching for the text works but i can't select it
#elem2.send_keys(Keys.DOWN)
#time.sleep(2)
#elem2.send_keys(Keys.DOWN)
#time.sleep(2)
#elem2.send_keys(Keys.RETURN)
#elem2.submit()
elem2.select_by_visible_text('Premier League')
Upvotes: 2
Views: 1393
Reputation: 193088
As you have tried to identify the Search Box
through classname
identifies as follows :
elem = browser.find_element_by_class_name('sp-c-date-picker-timeline__item')
#and
elem2=browser.find_element_by_class_name('sp-c-search__input')
These locators doesn't identifies the Search Box
uniquely.
To input some text in a search box
you have to identify the Search Box
with placeholder set to Enter a team or competition
through a unique CSS
or XPATH
as follows :
driver.find_element_by_xpath("//input[@id='sp-c-search__input']").send_keys("premier league")
Finally, to click()
on the option with text as Premier League
you can use the following code block :
suggestions = WebDriverWait(driver, 10).until(EC.presence_of_all_elements_located(By.XPATH,"//input[@id='sp-c-search__input']//following::div[@id='search-results']//ul/li/a/mark"))
for suggestion in suggestions :
if suggestion.get_attribute("innerHTML").contains("Premier League") :
suggestion.click()
As you are seeing the error as :
NameError: name 'By' is not defined
Ensure that you have added all the following imports :
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
Upvotes: 1