This code takes a website and downloads all .jpg images in the webpage. It supports only websites that have the <img>
element and src
contains a .jpg link.
import random
import urllib.request
import requests
from bs4 import BeautifulSoup
def Download_Image_from_Web(url):
source_code = requests.get(url)
plain_text = source_code.text
soup = BeautifulSoup(plain_text, "html.parser")
raw_text = r'links.txt'
with open(raw_text, 'w') as fw:
for link in soup.findAll('img'):
image_links = link.get('src')
if '.jpg' in image_links:
for i in image_links.split("\\n"):
fw.write(i + '\n')
num_lines = sum(1 for line in open('links.txt'))
if num_lines == 0:
print("There is 0 photo in this web page.")
elif num_lines == 1:
print("There is", num_lines, "photo in this web page:")
else:
print("There are", num_lines, "photos in this web page:")
k = 0
while k <= (num_lines-1):
name = random.randrange(1, 1000)
fullName = str(name) + ".jpg"
with open('links.txt', 'r') as f:
lines = f.readlines()[k]
urllib.request.urlretrieve(lines, fullName)
print(lines+fullName+'\n')
k += 1
Download_Image_from_Web("https://pixabay.com")