我似乎无法找到一种方法来单击正确的元素以获得我正在寻找的网址。本质上我想点击topYouTube 搜索中的视频(排名最高的返回视频)。
如何解决 ElementNotInteractableException:元素在 Selenium webdriver 中不可见? https://stackoverflow.com/questions/43868009/how-to-resolve-elementnotinteractableexception-element-is-not-visible-in-seleni-> 这是针对 Java 的,但它让我找到了正确的方向(知道我需要执行 JavaScript)
http://www.teachmeselenium.com/2018/04/17/python-selenium-interacting-with-the-browser-executing-javascript-through-javascriptexecutor/ http://www.teachmeselenium.com/2018/04/17/python-selenium-interacting-with-the-browser-executing-javascript-through-javascriptexecutor/-> 这向我展示了应该如何尝试在 python 中执行 javascript。
我也看过无数关于等待的文章,但它们并不能解决我的问题。
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()
I get a ElementNotVisibleException: Message: element not interactable
当我不执行任何 javascript 时出现错误(尽管它实际上已经工作过,但它远非健壮)。当我执行 JavaScript 时,它点击了错误的视频。
我已经尝试了所有类型的等待“显式”和“隐式”,现在确实有效。
我很确定我需要执行一些 JavaScript,但我不知道如何执行。