我似乎无法找到一种方法来单击正确的元素以获取所需的网址。本质上,我试图在youtube搜索中单击 顶部 视频(返回最高排名的视频)。
如何解决ElementNotInteractableException:元素在SeleniumWebdriver中不可见? ->这是针对Java的,但是它让我朝着正确的方向前进(知道我需要执行JavaScript)
http://www.teachmeselenium.com/2018/04/17/python-selenium-interacting-with- the-browser-executing-javascript-through- javascriptexecutor/- >这显示了我应该如何尝试在蟒蛇。
我也看过无数关于等待的文章,但是它们并不能解决我的问题。
from selenium import webdriver from selenium.webdriver.common.keys import Keys import time wrds = ["Vivaldi four seasons", "The Beatles twist and shout", "50 cent heat"] #Random list of songs driver = webdriver.Chrome() for i in wrds: driver.get("http://www.youtube.com") elem = driver.find_element_by_id("search") elem.send_keys(i) elem.send_keys(Keys.RETURN) time.sleep(5) driver.execute_script("arguments[0].click()",driver.find_element_by_id('video-title')) #THIS CLICKS ON WRONG VIDEO #elem = driver.find_element_by_id("video-title").click() #THIS FAILS time.sleep(5) url = driver.current_url driver.close()
ElementNotVisibleException:Message:elementnotinteractable当我不执行任何javascript时,我会收到一个错误消息(即使它实际上已经工作了,而且几乎没有健壮性)。当我执行JavaScript时,它会点击错误的视频。
ElementNotVisibleException:Message:elementnotinteractable
我尝试了所有类型的“显式”和“隐式”等待,现在它们确实起作用了。我很确定我需要执行一些JavaScript,但是我不知道该怎么做。
你快到了 您需要诱导 WebDriverWait 来使 元素可单击, 并且可以使用以下解决方案:
代码块:
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
wrds = [“Vivaldi four seasons”, “The Beatles twist and shout”, “50 cent heat”] kwrd = [“Vivaldi”, “Beatles”, “50”] options = webdriver.ChromeOptions() options.add_argument(“start-maximized”) options.add_argument(“disable-infobars”) options.add_argument(“–disable-extensions”) driver=webdriver.Chrome(chrome_options=options, executable_path=r’C:\WebDrivers\chromedriver.exe’) for i, j in zip(wrds, kwrd): driver.get("https://www.youtube.com/”) WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, “input#search”))).send_keys(i) driver.find_element_by_css_selector(“button.style-scope.ytd-searchbox#search-icon-legacy”).click() WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, “h3.title-and-badge.style-scope.ytd-video-renderer a”))).click() WebDriverWait(driver, 10).until(EC.title_contains(j)) print(driver.current_url) driver.quit()