【发布时间】:2019-07-04 02:08:45
【问题描述】:
我似乎无法找到一种方法来单击正确的元素以获取我正在寻找的 url。本质上,我试图点击 youtube 搜索中的 top 视频(排名最高的返回视频)。
How to resolve ElementNotInteractableException: Element is not visible in Selenium webdriver? -> 这是针对 Java 的,但它让我朝着正确的方向前进(知道我需要执行 JavaScript)
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()
当我不执行任何 javascript 时,我得到一个 ElementNotVisibleException: Message: element not interactable 错误(即使它实际上已经工作了,在它几乎没有鲁棒性之前)。当我执行 javascript 时,它会点击错误的视频。
我已经尝试了所有类型的“显式”和“隐式”等待,现在这确实有效。 我很确定我需要执行一些 JavaScript,但我不知道怎么做。
【问题讨论】:
-
见:stackoverflow.com/a/54551477/8179099 这可以给你一个线索,为什么它点击了错误的链接......
-
关闭,但这会返回链接的无序列表。我正在尝试单击(或以某种方式检索)top 链接。
标签: python-3.x selenium selenium-webdriver youtube webdriverwait