Rahul Shrivastava
Rahul Shrivastava

Reputation: 1411

How to get images from link?

When I'm trying to reach the image tag through this code I am getting following output.

url = 'https://paytm.com/shop/p/pepe-jeans-blue-slim-fit-t-shirts-APPPEPE-JEANS-BSETU2010438B648267'

def soup_maker(url):
    r = requests.get(url)
    markup = r.content
    soup = bs(markup, "html.parser")
    return soup

def get_images(url):
    soup = soup_maker(url)
    divs = soup.find_all('div', {'class': 'fixed-height'})
    print(divs)
    images = soup.find_all('img')
    print(images)

Output

[]
[<img alt="{{::product.text}}" ng-src="{{::product.image_url}}"/>, 
 <img alt="{{item.title}}" ng-src='{{cart.imgResized(item.image_url,"50x50") }}'/>, 
 <img ng-src="{{pixelSource}}"/>]

But when I am seeing through Inspect Element its there. I don't know how to save those images.

UPDATE

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

def soup_maker(url):
    driver = webdriver.Chrome()
    driver.get(url)
    try:
        element = WebDriverWait(driver, 20).until(
        EC.presence_of_element_located((By.CLASS_NAME, "fixed-height"))
        )
        markup = driver.page_source
        soup = bs(markup, "html.parser")
        return soup
    finally:
        driver.quit()
    driver.close()

Above worked for me.

Upvotes: 2

Views: 103

Answers (1)

alecxe
alecxe

Reputation: 473843

This looks like an AngularJS template with defined bindings which means the site needs a real browser with a javascript engine to be rendered in. Let's leave the parsing part as is, but instead of requests, get the source via selenium:

from selenium import webdriver

def soup_maker(url):
    driver = webdriver.Firefox()  # could also be Chrome(), PhantomJS() or other
    driver.get(url)

    # you might also need an Explicit Wait here to wait for the page to load
    # see http://selenium-python.readthedocs.org/waits.html#explicit-waits

    markup = driver.page_source
    driver.close()
    soup = bs(markup, "html.parser")
    return soup

Upvotes: 2

Related Questions