我正在尝试使用 selenium 和 python 在搜索框中输入一些文本。代码如下。如果选择“ super 联赛”选项,它运行得非常好。虽然输入此文本时,它会作为预定义选项出现在框中,但我无法根据需要选择并单击它...如果您正在浏览网页,则可以单击“英超联赛”选项,然后它加载新页面。我似乎无法复制这个
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')
最佳答案
正如您尝试通过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')
这些定位器不能唯一地标识搜索框
。
要在搜索框中输入一些文本
,您必须通过占位符设置为输入团队或比赛
来识别搜索框
独特的 CSS
或 XPATH
如下:
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
关于javascript - 在搜索框中输入文本,然后选择使用 Selenium 和 Python 自动完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48011101/