我正在尝试使用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')
答案 0 :(得分:1)
正如您尝试确定Search Box
到classname
标识如下:
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
,您必须通过唯一的Search Box
或Enter a team or competition
将占位符设置为CSS
的{{1}}标识如下:
XPATH
最后,对于带有 driver.find_element_by_xpath("//input[@id='sp-c-search__input']").send_keys("premier league")
文字的选项的click()
,您可以使用以下代码块:
Premier League
正如您所看到的错误:
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