Home > Mobile >  how to get img src url to python?
how to get img src url to python?

Time:06-25

I want to get the following scr url.

enter image description here

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from datetime import date
import openpyxl
import time

from webdriver_manager.chrome import ChromeDriverManager
driver = webdriver.Chrome(ChromeDriverManager().install())

img_class = 'thumbnail_thumb_wrap__1pEkS _wrapper' #div
img_xpath = '/html/body/div/div/div[2]/div[2]/div[3]/div[1]/ul/div/div[1]/li/div/div[1]/div/a/img'
img_css = '.thumbnail_thumb_wrap__1pEkS .thumbnail_thumb__3Agq6:before'

item_img = driver.find_elements(By.XPATH, img_xpath).__getattribute__('src')

print(item_img)

I searched by Xpath, css_select, and class_name, but I see an error message that none of them have 'src'. What am I missing here?

CodePudding user response:

I believe you have to use the .get_attribute("src") method, instead of the __getattribute__ method. The former is implemented by Selenium as a method to get an attribute from the webpage, while the latter is a builtin Python method to try and get the attribute of the Python object.

See here for the Selenium get_attribute documentation, and here for the Python __getattribute__ method that you should not use in this situation.


Example

from selenium import webdriver
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()

img_xpath = '/html/body/div[4]/main/div[1]/div[1]/div[1]/div/div/div[2]/div/div/img'
driver.get("https://github.com")
item_web_element = driver.find_element(By.XPATH, img_xpath)
item_img = item_web_element.get_attribute("src")
print("The source is:", item_img)

driver.quit()
  • Related