【问题标题】:How to wait until the src attribute is defined using Selenium and Python如何等到使用 Selenium 和 Python 定义 src 属性
【发布时间】:2020-07-06 11:31:48
【问题描述】:

我在 python 中用 selenium 编写了一个程序。 我的目标是在页面中找到视频的 src。 这是我的代码

video_element = chrome_driver.find_element_by_tag_name("video")
video_src = video_element.get_attribute("src")

当我尝试检查 video_src 时,我得到一个空字符串,但是如果我在尝试获取 src 之前输入 time.sleep(1),我会得到视频的真实链接。 我曾尝试使用WebDriverWait 而不是time.wait 像这样

video_element = WebDriverWait(chrome_driver, 3).until(
            expected_conditions.element_to_be_clickable((By.TAG_NAME, "video"))
        )

但我找不到任何等到 src 标签被真实链接填充的条件。 有没有办法用硒而不是时间来等待? (随着时间的推移,不保证src会被填满)

【问题讨论】:

标签: python-3.x selenium xpath webdriverwait tagname


【解决方案1】:

在您必须切换到 iframe 之前,请尝试以下解决方案

from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait as Wait
from selenium.webdriver.support.ui import WebDriverWait
from selenium import webdriver
driver = webdriver.Chrome(executable_path=r"C:\New folder\chromedriver.exe")
driver.get('https://www.thewatchcartoononline.tv/www-working-episode-1-english-subbed')
driver.switch_to.frame("anime-js-0")
video_element = WebDriverWait(driver, 3).until(EC.visibility_of_element_located((By.ID, "video-js_html5_api")))
val = video_element.get_attribute("src")
print val

输出:

【讨论】:

  • 我在切换之前尝试这样做,但出现超时异常(因为 selenium 找不到视频标签)。当我在切换后尝试您的解决方案时,它确实有效,但只有当我使用 timeout=20 时,如果我使用 timeout=3 则它不起作用。这告诉我它的行为就像 time.sleep
  • 我也遇到了和以前一样的问题,请检查你的代码timeout=3而不是20,你也没有使用你创建的chrome_option,你是故意的吗?
  • 我已删除 chrome_option 并将 WebDriverWait 更改为 3 对我来说仍然可以正常工作。请检查更新的解决方案
  • 你说得对,我忘了把定位器改成 id 而不是标签名
【解决方案2】:

你可以试试下面的。

video_element = WebDriverWait(chrome_driver, 3).until(
            expected_conditions.presence_of_element_located((By.XPATH, "//video[not(@src='')]"))
        )

【讨论】:

  • 它不起作用,您愿意解释一下您使用的xpath吗?
  • 等到video 元素的src 属性值不等于""
  • 它似乎应该工作,我不知道为什么它不工作。你自己检查了吗?
【解决方案3】:

要提取 src 属性的值,您必须为所需的visibility_of_element_located() 诱导 WebDriverWait,您可以使用以下任一Locator Strategies

  • 使用CSS_SELECTOR

    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.TAG_NAME, "video"))).get_attribute("innerHTML"))
    
  • 使用XPATH

    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//video"))).get_attribute("src"))
    
  • 注意:您必须添加以下导入:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    

【讨论】:

    猜你喜欢
    • 2021-12-31
    • 1970-01-01
    • 2021-09-09
    • 2021-05-19
    • 1970-01-01
    • 2019-03-02
    • 2020-09-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多