我似乎无法找到一种方法,点击右边的元素,为了得到我要找的URL。从本质上讲,我想点击一个YouTube搜索上的视频(排名最高的返回视频)。
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,但我不知道怎么办。
你是几乎没有。你需要引起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()
这就是你永远不应该使用JavaScript点击的原因之一,硒webdriver的目的是刺激,就好像一个真实的用户能够点击。真正的用户不能在页面上点击一个无形的元素,但你可以通过JavaScript点击。如果您通过ID video-title
搜索元素,它完全符合影片53。但我不知道你要点击哪一个。您可以通过其他方式(而不是由ID)相匹配的元素。
我会给你一个想法如何单击元素,但你点击之前,你需要先找出指标。
driver.find_element_by_xpath("(//*[@id='video-title'])[1]").click
如果第一个是不可见的,然后通过2,[2]然后是三个,找出它的单击所需的元件是哪一个。或者,您可以指定确切的元素,我们可能会通过一些其他的方式来定位元素。