Selenium Python Get Img SRC Returns Actual Image Data

萝らか妹 提交于 2021-02-10 12:22:31

问题


I am working with Selenium in Python and using Firefox web driver.

I am trying to get the SRC of an image. When I first request the SRC I get the actual image data, not the SRC

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

If I run the exact same code a second time I will get the SRC

example.jpg

Here is my code

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)

Not sure why the image data is being returned on the first time the code is ran, and then the src in the second run. It almost seems that once the image is cached then it can get the src or something like that.

Any suggestions on how to prevent the image data from being returned, just the src link?

Thanks


回答1:


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 Locator Strategies:

  • Using ID:

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

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

    print(WebDriverWait(browser, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "#idOfImageHere"))).get_attribute("src"))
    
  • Note : You have to add the following imports :

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


来源:https://stackoverflow.com/questions/59689416/selenium-python-get-img-src-returns-actual-image-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!