在Python上使用Selenium返回空'src'属性

问题描述 投票:0回答:1

我是一名新手程序员,我正在教自己一些网页编写。我正在尝试制作一个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>

视频元素最初没有src属性。但是当我在浏览器上单击上面的按钮时,页面似乎运行了一些javascripts,视频元素获得了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: 

正如您所看到的,我可以准确地获取'class'和'id'信息,但'src'标记始终返回空。但是如果我使用Chrome打开网站并手动点击按钮,我可以看到src字段按预期填充。

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

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

python selenium web-scraping selenium-chromedriver
1个回答
0
投票

我想点击“按钮”和src后出现在视频元素中需要一些时间(可能是ms)。由于视频元素始终存在,因此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")
© www.soinside.com 2019 - 2024. All rights reserved.