Search code examples
pythonlistseleniumselenium-webdrivergetattribute

Get the src value from a list of webelements with Selenium


Hello trying to adapt a solution from this video

#scroller 100 fois pour reveler le plus d'image ( comment etre sur qu'on est à la fin ?)
n_scrolls = 100
for i in range(1, n_scrolls):
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    time.sleep(5)
    #recupère toutes les balises img puis leurs attribut src (je ne comprend pa bien cette façon d'assigner les elements)
    images = driver.find_elements_by_tag_name('img')
    print(images)
    images = [images.get_attribute('src') for img in images]

But the output is:

[<selenium.webdriver.remote.webelement.WebElement (session="50f35cc8388f3b59df4042bcc09c7079", element="4a4b2838-67d6-4787-a168-9e25e948a21a")>, <selenium.webdriver.remote.webelement.WebElement (session="50f35cc8388f3b59df4042bcc09c7079", element="7e3ae8f5-160a-4da6-b3a7-2be10bad8f3f")>, <selenium.webdriver.remote.webelement.WebElement (session="50f35cc8388f3b59df4042bcc09c7079", element="8c45c421-3f25-4498-85a2-565506835984")>, <selenium.webdriver.remote.webelement.WebElement (session="50f35cc8388f3b59df4042bcc09c7079", element="5ef69be7-13d7-41f1-9ec8-d8ac6e843fdd")>, <selenium.webdriver.remote.webelement.WebElement (session="50f35cc8388f3b59df4042bcc09c7079", element="626ae474-bccc-40c3-ac60-5b5f021b7bf0")>, <selenium.webdriver.remote.webelement.WebElement (session="50f35cc8388f3b59df4042bcc09c7079", element="ea0b589d-8e90-470a-ad59-a661f8d52b31")>

Instead of the img tag element, is it possible to get the src attributes?


Solution

  • I can find the mistake you have made.

    Instead of this

    images = [images.get_attribute('src') for img in images]
    

    It should be

    images = [img.get_attribute('src') for img in images]
    

    Since you are iterating the list.

    Now print the list you will get all src values.

    print(images)