Selenium Python 获取 Img SRC Returns 实际图像数据

Selenium Python Get Img SRC Returns Actual Image Data

我在 Python 中使用 Selenium 并使用 Firefox Web 驱动程序。

我正在尝试获取图像的 SRC。当我第一次请求 SRC 时,我得到的是实际图像数据,而不是 SRC

data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQ ...

如果我 运行 第二次使用完全相同的代码,我将获得 SRC

example.jpg

这是我的代码

fireFoxOptions = webdriver.FirefoxOptions()
fireFoxOptions.set_headless()
browser = webdriver.Firefox(firefox_options=fireFoxOptions)

element = browser.find_element(By.ID , "idOfImageHere" )
imageUrl = element.get_attribute("src")
print("image src: " + imageUrl)

不确定为什么第一次返回图像数据的代码是 运行,然后是第二个 运行 中的 src。似乎一旦图像被缓存,它就可以获得 src 或类似的东西。

关于如何防止返回图像数据的任何建议,只是 src link?

谢谢

Amazon website elements are JavaScript enabled elements so to extract the src attribute of any element, you have to induce WebDriverWait for the visibility_of_element_located() and you can use either of the following :

  • 使用ID:

    print(WebDriverWait(browser, 20).until(EC.visibility_of_element_located((By.ID, "idOfImageHere"))).get_attribute("src"))
    
  • 使用XPATH:

    print(WebDriverWait(browser, 20).until(EC.visibility_of_element_located((By.XPATH, "//*[@id='idOfImageHere]"))).get_attribute("src"))
    
  • 使用CSS_SELECTOR:

    print(WebDriverWait(browser, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "#idOfImageHere"))).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