orie
orie

Reputation: 571

using BeautifulSoup to print images from a website

I'm practicing using BeautifulSoup in python, trying to parse information from this website:

https://www.vogue.com/fashion/street-style

how would you print images from the website? for example I tried to parse the logo which exists here in the HTML:

from bs4 import BeautifulSoup
import requests

source = requests.get('https://www.vogue.com/fashion/street-style').text

soup = BeautifulSoup(source, 'lxml')

logo = soup.find('img', class_='logo--image')
print(logo)

this prints out:

<img alt="Vogue Logo" class="logo--image" src="/img/vogue-logo-pride.svg"/>

How do I print the actual picture in my editor?

Upvotes: 0

Views: 584

Answers (1)

Thomas
Thomas

Reputation: 899

Quick Summary

Unfortunately, modern editors/terminals support text, not images. There are some alternatives:

  • Option 1: Download the image and open it regularly.

  • Option 2: Open a new browser tab with the image.

Solution

Option 1

from bs4 import BeautifulSoup
import requests
import shutil

WEBSITE = 'https://www.vogue.com/fashion/street-style'
SAVE_LOCATION = 'downloaded.svg'  # name of file to save image to

source = requests.get(WEBSITE).text

soup = BeautifulSoup(source, 'lxml')

relative_link_to_logo = soup.find('img', class_='logo--image')['src']

img = requests.get(f'{WEBSITE}/{relative_link_to_logo}', stream=True)
with open(SAVE_LOCATION,'wb') as f:
    for chunk in img:
        f.write(chunk)

Option 2

from bs4 import BeautifulSoup
import requests
import webbrowser

WEBSITE = 'https://www.vogue.com/fashion/street-style'

source = requests.get(WEBSITE).text

soup = BeautifulSoup(source, 'lxml')

relative_link_to_logo = soup.find('img', class_='logo--image')['src']

webbrowser.open(f'{WEBSITE}/{relative_link_to_logo}')

Final Remarks

Some editors like Visual Studio Code have plugins that let you preview an image file (that you've downloaded to your computer) without leaving the editor. This still involves Option 1, downloading to disk.

I hope this helps you!

Upvotes: 1

Related Questions