简体   繁体   中英

Scraping html for img src in Python bs4

I have the following HTML code I am trying to parse with BeautifulSoup in Python, or bs4:

  <div class="product w-100" data-pid="BBOMNLV1-36183" data-sid="BBOMNLWB">
        <div class="product-tile w-100">
            <!-- dwMarker="product" dwContentID="c4e921241579720afa4287dbf5" -->
            <div class="image-container">
                <a href="/pd/omn1s-low/BBOMNLV1-36183.html?dwvar_BBOMNLV1-36183_style=BBOMNLWB">
                    <picture>
                        <source type="image/jpeg" data-srcset="https://nb.scene7.com/is/image/NB/bbomnlwb_nb_02_i?$pdpflexf2$&amp;wid=440&amp;hei=440 1x, https://nb.scene7.com/is/image/NB/bbomnlwb_nb_02_i?$pdpflexf2$&amp;wid=880&amp;hei=880 2x" srcset="https://nb.scene7.com/is/image/NB/bbomnlwb_nb_02_i?$pdpflexf2$&amp;wid=440&amp;hei=440 1x, https://nb.scene7.com/is/image/NB/bbomnlwb_nb_02_i?$pdpflexf2$&amp;wid=880&amp;hei=880 2x"> <img class="tile-image ls-is-cached lazyloaded" src="https://nb.scene7.com/is/image/NB/bbomnlwb_nb_02_i?$pdpflexf2$&amp;wid=440&amp;hei=440" data-src="https://nb.scene7.com/is/image/NB/bbomnlwb_nb_02_i?$pdpflexf2$&amp;wid=440&amp;hei=440" data-srcset="https://nb.scene7.com/is/image/NB/bbomnlwb_nb_02_i?$pdpflexf2SM$&amp;wid=440&amp;hei=440 1x, https://nb.scene7.com/is/image/NB/bbomnlwb_nb_02_i?$pdpflexf2SM$&amp;wid=880&amp;hei=880 2x" alt="OMN1S Low" title="OMN1S Low, BBOMNLWB" itemprop="image" srcset="https://nb.scene7.com/is/image/NB/bbomnlwb_nb_02_i?$pdpflexf2SM$&amp;wid=440&amp;hei=440 1x, https://nb.scene7.com/is/image/NB/bbomnlwb_nb_02_i?$pdpflexf2SM$&amp;wid=880&amp;hei=880 2x"> </picture>
                </a>
                <div class="product-id d-none">BBOMNLV1-36183</div>
                <div class="wishlist-url d-none">/on/demandware.store/Sites-NBUS-Site/en_US/Wishlist-WishlistItemExists</div> <span class="wishListToggle">
                <a class="wishlistTile add-to-wish-list" href="/on/demandware.store/Sites-NBUS-Site/en_US/Wishlist-AddProduct" title="Wish list">
                    <span class="wishlist-inactive active">
    <svg role="img" class="icon svg-icon " width="24" height="24" aria-label="title">
    <title> </title>
    <desc> </desc>
    <use xlink:href="#wishlist-inactive"></use>
    </svg></span> </a>
                <a class="wishlistTile remove-from-wishlist" href="/on/demandware.store/Sites-NBUS-Site/en_US/Wishlist-RemoveProduct" title="Wish list"> <span class="wishlist-active ">
    <svg role="img" class="icon svg-icon " width="24" height="24" aria-label="title">
    <title> </title>
    <desc> </desc>
    <use xlink:href="#wishlist-active"></use>
    </svg></span> </a>
                </span>
            </div>
            <div class="tile-body">
                <div class="row pgp-grid pb-2 pr-2">
                    <div class="col-12 col-lg-7 pl-2 fw-search">
                        <div class="pdp-link"> <a class="link font-weight-bold pname text-underline no-underline-lg" href="/pd/omn1s-low/BBOMNLV1-36183.html?dwvar_BBOMNLV1-36183_style=BBOMNLWB">OMN1S Low</a> <span class="category-name font-body w-100 d-block pt-2">
            
                Men's Basketball
            
        </span> </div>
                    </div>
                    <div class="col-12 col-lg-5 pl-2 fw-search justify-content-lg-end text-right d-flex p-0 search-tile">
                        <div class="price"> <span class="price-value">
        
    
        
        <span class="sales font-body-large ">
            
            
            
            $139.99
    
    
        </span> </span>
                        </div>
                    </div>
                </div>
                <div class="pgp-reviews-wrapper" data-pageid="BBOMNLV1-36183" data-url="https://www.newbalance.com/on/demandware.store/Sites-NBUS-Site/en_US/ProductReviews-WriteReview?pid=BBOMNLV1-36183" id="BBOMNLV1-36183-pgp-reviews-wrapper-3">
                    <div class="p-w-r">
                        <section id="pr-category-snippets-BBOMNLV1-36183" class="pr-no-reviews" aria-labelledby="pr-UbCtutN-xQJECAE6zEJSy" data-testid="category-snippet">
                            <div class="pr-snippet pr-category-snippet">
                                <div class="pr-category-snippet__rating pr-category-snippet__item">
                                    <div class="pr-snippet-stars pr-snippet-stars-png ">
                                        <div aria-hidden="true" class="pr-rating-stars">
                                            <div class="pr-star-v4 pr-star-v4-0-filled"></div>
                                            <div class="pr-star-v4 pr-star-v4-0-filled"></div>
                                            <div class="pr-star-v4 pr-star-v4-0-filled"></div>
                                            <div class="pr-star-v4 pr-star-v4-0-filled"></div>
                                            <div class="pr-star-v4 pr-star-v4-0-filled"></div>
                                        </div>
                                        <div aria-hidden="true" class="pr-snippet-rating-decimal">0.0</div>
                                    </div><span id="pr-UbCtutN-xQJECAE6zEJSy" class="pr-accessible-text">Rated 0 out of 5 stars</span></div>
                                <div class="pr-category-snippet__total pr-category-snippet__item">No Reviews</div>
                            </div>
                        </section>
                    </div>
                </div>
            </div>
            <div class="badges"> <span class="sub-badges p-1 text-uppercase font-weight-bold">NEW</span> </div>
            <!-- END_dwmarker -->
        </div>
    </div>

I am trying to retrieve the shoe's pciture by finding img tag with the class "tile-image ls-is-cached lazyloaded", then I try to retrieve the data-src attribute to acquire the link of the photograph.

Here is my bs4 code, which does not seem to work:

from bs4 import BeautifulSoup
def queryNewBalance(uri):
    r = requests.get('https://www.newbalance.com/men/shoes/basketball/?prefn1=color&prefv1=Black%7CBlue&srule=null')
    soup = BeautifulSoup(r.content, 'html.parser')
    result = soup.find_all('div', class_='product w-100')
    for res in result:
        print("*******************************")
        print(res.find('img', class_='tile-image ls-is-cached lazyloaded')['href]) #Picture
        print("*******************************")
    print(f"\nFound total shoes: {len(result)}")

How do I fix my code to retrieve the image link?

It seems that the attribute you are getting is href the <img> tag you are trying to scrape doesn't have that attribute , it has the src attribute and that is where the link is. By the way put your html parameter that long html code you provided.

def queryNewBalance(html):
    #r = requests.get('https://www.newbalance.com/men/shoes/basketball/?prefn1=color&prefv1=Black%7CBlue&srule=null')
    soup = BeautifulSoup(html, 'html.parser')
    result = soup.find_all('div', class_='product w-100')
    for res in result:
        print("*******************************")
        print(res.find('img', class_='tile-image ls-is-cached lazyloaded')['src']) #Picture
        print("*******************************")
    print(f"\nFound total shoes: {len(result)}")



queryNewBalance(html)

Output

*******************************
https://nb.scene7.com/is/image/NB/bbomnlwb_nb_02_i?$pdpflexf2$&wid=440&hei=440
*******************************

Found total shoes: 1
[Finished in 0.7s]

--- URL ---

from bs4 import BeautifulSoup
import requests

def queryNewBalance():
    r = requests.get('https://www.newbalance.com/men/shoes/basketball/?prefn1=color&prefv1=Black%7CBlue&srule=null')
    soup = BeautifulSoup(r.content, 'html.parser')
    result = soup.find_all('div', class_='product w-100')
    for res in result:
        print("*******************************")
        print(res.find('img', class_='tile-image')["data-src"]) #Picture
        print("*******************************")
    print(f"\nFound total shoes: {len(result)}")



queryNewBalance()

Output:

*******************************
https://nb.scene7.com/is/image/NB/bbomnxbb_nb_02_i?$pdpflexf2$&wid=440&hei=440
*******************************
*******************************
https://nb.scene7.com/is/image/NB/bbomnlpl_nb_02_i?$pdpflexf2$&wid=440&hei=440
*******************************
*******************************
https://nb.scene7.com/is/image/NB/bbomnlwb_nb_02_i?$pdpflexf2$&wid=440&hei=440
*******************************
*******************************
https://nb.scene7.com/is/image/NB/bbomnlbr_nb_02_i_5a34b3da900d437a9a88?$pdpflexf2$&wid=440&hei=440
*******************************
*******************************
https://nb.scene7.com/is/image/NB/bbomnlfc_nb_02_i?$pdpflexf2$&wid=440&hei=440
*******************************
*******************************
https://nb.scene7.com/is/image/NB/bbomnlwt_nb_02_i?$pdpflexf2$&wid=440&hei=440
*******************************

Found total shoes: 6
[Finished in 2.9s]

PS: If you are getting involved more with web scraping, and scraping tons of websites especially the big ones, I suggest you change your parser to html5lib -> pip install html5lib . It's a better parser as I've had problems scraping with html.parser , it just doesn't somehow scrape some part of a website tho I've check the soup object where it has, anyways your call, Good luck!

There's no class tile-image ls-is-cached lazyloaded on the page. To get the links of the images, you can use a CSS Selector img[itemprop='image'] :

import requests
from bs4 import BeautifulSoup

def queryNewBalance(url):
    r = requests.get(url)
    soup = BeautifulSoup(r.content, "html.parser")
    result = soup.find_all("div", class_="product w-100")
    for res in result:
        print("*******************************")
        print(res.select_one("img[itemprop='image']")["data-src"])
    print(f"\nFound total shoes: {len(result)}")


queryNewBalance(
    "https://www.newbalance.com/men/shoes/basketball/?prefn1=color&prefv1=Black%7CBlue&srule=null"
)

Output:

*******************************
https://nb.scene7.com/is/image/NB/bbomnxbb_nb_02_i?$pdpflexf2$&wid=440&hei=440
*******************************
https://nb.scene7.com/is/image/NB/bbomnlpl_nb_02_i?$pdpflexf2$&wid=440&hei=440
*******************************
https://nb.scene7.com/is/image/NB/bbomnlwb_nb_02_i?$pdpflexf2$&wid=440&hei=440
*******************************
https://nb.scene7.com/is/image/NB/bbomnlbr_nb_02_i_5a34b3da900d437a9a88?$pdpflexf2$&wid=440&hei=440
*******************************
https://nb.scene7.com/is/image/NB/bbomnlfc_nb_02_i?$pdpflexf2$&wid=440&hei=440
*******************************
https://nb.scene7.com/is/image/NB/bbomnlwt_nb_02_i?$pdpflexf2$&wid=440&hei=440

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM