首页 > 解决方案 > 在 Python 上使用 Selenium 返回的空“src”属性

问题描述

我是一个菜鸟程序员,我正在自学一些网页抓取。我正在尝试制作一个 Python 程序,该程序通过使用 selenium 抓取网页来从嵌入式播放器返回直接视频下载 URL。

所以这是网页的相关html:

<video class="vjs_tech" id="olvideo_html5_api" crossorigin="anonymous"></video>
<button class="vjs-big-play-button" type="button" aria-live="polite" title="Play Video" aria-disabled="false"><span class="vjs-control-text">Play Video</span></button>

video 元素最初没有 src 属性。但是当我在浏览器上单击上面的按钮时,页面似乎运行了一些 javascript,并且视频元素获得了 src 属性。我想将此 src 属性的内容打印到监视器。所以这就是我在python中复制这个过程的方式:

#Clicking the Button
playbutton = driver.find_element_by_tag_name('button')
playbutton.send_keys(Keys.RETURN)

#Selecting the Video Element
wait = WebDriverWait(driver, 5)
video = wait.until(EC.visibility_of_element_located((By.TAG_NAME, 'video')))

#Printing the details of the Video Element
print "Class: ", video.get_attribute("class")
print "ID: ", video.get_attribute("id")
print "SRC: ", video.get_attribute("src")

输出如下所示:

Class: vjs_tech
ID: olvideo_html5_api
SRC: 

如您所见,我可以准确地获取“类”和“id”信息,但“src”标签总是返回空。但是,如果我使用 Chrome 打开站点并手动单击按钮,我可以看到 src 字段按预期填充。

我究竟做错了什么?如何让 src 属性显示在我的输出中?

(我在 Python27 上使用 Selenium 和 ChromeDriver。)

标签: pythonseleniumweb-scrapingselenium-chromedriver

解决方案


我想在您单击“按钮”和 src 后需要一些时间(可能是毫秒)才能出现在视频元素中。由于视频元素始终存在,webdriver 将获得其当前状态(即没有 src )。隐式/显式等待在这里无济于事,在这种情况下,您将需要使用 time.sleep

import time

#Clicking the Button
playbutton = driver.find_element_by_tag_name('button')
playbutton.send_keys(Keys.RETURN)
time.sleep(5) #<<<<<<<<<<<<<<<to add 5 sec sleep, you can adjust this

#Selecting the Video Element
video = driver.find_element_by_tag_name('video')

#Printing the details of the Video Element
print "Class: ", video.get_attribute("class")
print "ID: ", video.get_attribute("id")
print "SRC: ", video.get_attribute("src")

推荐阅读