【问题标题】:Empty 'src' attribute returned with Selenium on Python在 Python 上使用 Selenium 返回的空“src”属性
【发布时间】:2019-03-02 10:50:33
【问题描述】:

我是一名新手程序员,我正在自学一些网络爬虫。我正在尝试制作一个 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 属性。但是当我在浏览器上单击上面的按钮时,页面似乎运行了一些 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。)

【问题讨论】:

标签: python selenium web-scraping selenium-chromedriver


【解决方案1】:

我想在您单击“按钮”和 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")

【讨论】:

  • 这是为我做的......虽然有点原始,但很简单,但可以节省大量时间!!!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-09
  • 2019-01-10
  • 1970-01-01
  • 2020-07-06
  • 2021-05-19
  • 2022-10-14
相关资源
最近更新 更多