【问题标题】:Inputting text in search box and then selecting from Auto Complete with Selenium and Python在搜索框中输入文本,然后从 Auto Complete with Selenium 和 Python 中进行选择
【发布时间】:2018-01-08 20:19:38
【问题描述】:

我正在尝试使用 selenium 和 python 在搜索框中输入一些文本。代码如下。如果选择“超级联赛”选项,它运行得非常好。虽然当输入此文本时,它作为预定义选项出现在框中加载一个新页面。我似乎无法复制这个

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')

【问题讨论】:

    标签: javascript python ajax selenium autocomplete


    【解决方案1】:

    由于您尝试识别Search Boxclassname,识别如下:

    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')
    

    这些定位器不能唯一标识Search Box

    对于input some text in a search box,您必须通过唯一的CSSXPATH 将占位符设置为Enter a team or competition 来识别Search Box,如下所示:

    driver.find_element_by_xpath("//input[@id='sp-c-search__input']").send_keys("premier league")
    

    最后,在文本为 Premier League 的选项上click(),您可以使用以下代码块:

    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()
    

    更新

    正如您所看到的错误:

    NameError: name 'By' is not defined
    

    确保您已添加以下所有导入:

    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
    

    【讨论】:

    • 似乎对我不起作用。我收到以下错误。它适合你吗?建议 = WebDriverWait(browser, 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"))) NameError: name 'By' is not defined
    • 更新了我的答案。让我知道状态。
    猜你喜欢
    • 2014-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-21
    • 1970-01-01
    • 1970-01-01
    • 2014-10-31
    • 2022-01-06
    相关资源
    最近更新 更多