Search code examples
web-scrapingxpath-2.0xpath-1.0

XPATH how to get the attr by selecting the class


I want to get the value of the attibute of an image like 'src'. also the image have a classname, i select the image using the class name, but how can i get the attribute?

<img src="http://somelink.jpg" class="img-fluid">

here's how i use the xpath selector to select an image using the classname

//img[@class="img-fluid"]

how can i get the value of an attr of an image "src"? so i'll have the link "http://somelink.jpg"?


Solution

  • You can use the below xpath to get the src value.

    //img[@class="img-fluid"]/@src
    

    For example, you can get src attribute of all avatar images in this page using the below xpath.

    //*[contains(@class, "user-gravatar")]//img/@src
    

    You may also take a look at this xpath cheatsheet.