从网页上抓取YouTube链接
我一直在尝试从网页上抓取YouTube链接,但没有任何效果。这是我一直试图抓取的图片。
这是我最近尝试过的代码:
youtube_link = soup.find("a", class_="ytp-title-link yt-uix-sessionlink")
这是YouTube链接所在网站的链接:https : //www.electronic-festivals.com/event/i-am-hardstyle-
germany
回答:
大多数youtube链接都位于iframe
和内,并且javascript也需要运行。尝试使用硒。以下提取任何src
或href
包含youtub
e。我只输入托管YouTube剪辑的关键iframe。您可以循环所有iframes
检查。
from selenium import webdriverfrom selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
def addItems(links, final):
for link in links:
ref = link.get_attribute('src') if link.get_attribute('src') is not None else link.get_attribute('href')
final.append(ref)
return final
url = "https://www.electronic-festivals.com/event/i-am-hardstyle-germany"
driver = webdriver.Chrome()
driver.get(url)
driver.switch_to.frame(driver.find_element_by_css_selector('.media-youtube-player'))
final = []
try:
links = WebDriverWait(driver, 10).until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, "[href*=youtube] , [src*=youtube]")))
addItems(links, final)
except:
pass
finally:
driver.switch_to.default_content()
links = driver.find_elements_by_css_selector('[href*=youtube] , [src*=youtube]')
addItems(links, final)
for link in set(final):
print(link)
driver.quit()
以上是 从网页上抓取YouTube链接 的全部内容, 来源链接: utcz.com/qa/405231.html