python - 在 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。)
解决方案
我想在您单击“按钮”和 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")
推荐阅读
- python - Python按字典中的多个键分组
- td-engine - TDengine中count(tbname)的性能问题
- reactjs - 使用 react-chartjs-2 制作固定的 y 轴刻度
- c++ - swscanf 在铸造中的实现
- windows - 使用 PowerShelll 将 Microsoft Edge 设置为默认浏览器
- python - 旋转令牌的时间限制函数
- azure - Azure 存储帐户在没有“blob.core.windows.net”端点的情况下创建
- heroku - ERR_CERT_DATE_INVALID 使用 Heroku ACM
- python - 无法通过 HTML 表单更改图像,但我可以从 Django 管理面板更改它们
- git - git 命令失败,退出代码 128 警告:url 在其用户名组件中包含换行符然后致命:无法解析凭据 url