from selenium import webdriver
from time import sleep
driver = webdriver.Chrome()
video = "YzmI5F_Yu1o"
driver.execute_script("window.open('about:blank');")
driver.switch_to_window(driver.window_handles[1])
driver.get("https://www.youtube.com/v/" + video)
title = driver.find_element_by_css_selector('.ytp-title-link.yt-uix-sessionlink')
返回
Traceback (most recent call last):
File "C:\Users\Gebruiker\Documents\playlist.py", line 36, in <module>
add_yt("YzmI5F_Yu1o")
File "C:\Users\Gebruiker\Documents\playlist.py", line 33, in add_yt
title = driver.find_element_by_css_selector('.ytp-title-link.yt-uix-sessionlink')
File "C:\Users\Gebruiker\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 498, in find_element_by_css_selector
return self.find_element(by=By.CSS_SELECTOR, value=css_selector)
File "C:\Users\Gebruiker\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 832, in find_element
'value': value})['value']
File "C:\Users\Gebruiker\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 297, in execute
self.error_handler.check_response(response)
File "C:\Users\Gebruiker\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 194, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":".ytp-title-link.yt-uix-sessionlink"}
(Session info: chrome=60.0.3112.101)
(Driver info: chromedriver=2.31.488763 (092de99f48a300323ecf8c2a4e2e7cab51de5ba8),platform=Windows NT 6.1.7601 SP1 x86_64)
基本上,它表示没有css选择器.ytp-title-link.yt-uix-sessionlink的元素,即使显而易见。
我试图返回的元素;
<a class="ytp-title-link yt-uix-sessionlink" target="_blank" data-
sessionlink="feature=player-title" href="https://www.youtube.com/watch?
v=YzmI5F_Yu1o">Marco Borsato - Mooi (official video)</a>
答案 0 :(得分:0)
尝试切换到embed
元素,就像iframe
一样,并获取所需的文字:
driver.switch_to.frame(driver.find_element_by_xpath('//embed'))
title = driver.find_element_by_xpath('//a[@data-sessionlink="feature=player-title"]').text