我用 selenium 进入YouTube,在搜索栏上写一些东西,然后按下按钮或回车键。
我试着用WebDriverWait
等待,我甚至把等待时间从10秒改为20秒,但没有任何区别。
而且如果我添加任何东西(比如打印新的页面标题),它只会向我显示第一页标题,而不是搜索后的标题。
下面是我的代码和我的尝试:
from selenium import webdriver
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
def get_driver():
firefox_options = Options()
# firefox_options.add_argument("--headless")
driver = webdriver.Firefox(executable_path=r"C:\Program Files\Mozilla Firefox\geckodriver.exe", options=firefox_options)
driver.implicitly_wait(9)
return driver
driver = get_driver()
driver.get('https://www.youtube.com/')
search = driver.find_element(By.XPATH, '//input[@id="search"]')
search.send_keys("python")
# search.send_keys(Keys.ENTER) #using the enter key # If I add nothing after this line it work
# searchbutton = driver.find_element(By.XPATH,'//*[@id="search-icon-legacy"]') # This also dose doesn't work
# searchbutton.click() # using the click method() #also dose not work
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="search-icon-legacy"]'))).click() # Sometimes work
# driver.implicitly_wait(10)
# print(driver.title) # This show me only the title of the first page not the one after the search
是因为我使用了Firefox webdriver(我应该换成Chrome吗)?还是因为我的互联网连接?
1条答案
按热度按时间s71maibg1#
要使其正常工作,您需要先单击搜索字段输入,然后添加一个短延迟,然后发送
Keys.ENTER
或单击search-icon-legacy
元素。所以,这不是你的错,这是YouTube网页的工作方式。你甚至可以称之为一种bug。但由于这个网页是为人类用户建立的,它工作得很好,因为人类永远不会在零时间内点击输入字段并插入搜索值。
无论如何,以下2个代码都有效:
第一次。
第二个。