1

I am new to web scraping I don't know much about it. I have made a bit of program which fetches a random image link from a website , But I get a list of links while doing so I am not getting a single link

HERE'S MY CODE

from bs4 import BeautifulSoup
import urllib.parse
from urllib.request import urlopen,Request
import random


requester = {'User-Agent': 'Mozilla/5.0'}
req=Request("https://image.com",headers=requester)
u =urlopen(req)


soup = BeautifulSoup(u.read(), features="lxml")



links = soup.find_all('a')

images =[]
for img in soup.findAll('img'):
    images.append(img.get('src'))
    img=random.choice(images)
    
    print(img)

HERE'S THE OUTPUT

https://www.bing.com/th?id=OHR.LongIsland_EN-US4283514207_1920x1080.jpg&rf=LaDigue_1920x1080.jpg&pid=hp
https://www.bing.com/th?id=OHR.BeaverDam_EN-US4184266799_1920x1080.jpg&rf=LaDigue_1920x1080.jpg&pid=hp
https://www.bing.com/th?id=OHR.PicoIsland_EN-US3959411167_1920x1080.jpg&rf=LaDigue_1920x1080.jpg&pid=hp
https://www.bing.com/th?id=OHR.LongIsland_EN-US4283514207_1920x1080.jpg&rf=LaDigue_1920x1080.jpg&pid=hp
https://www.bing.com/th?id=OHR.FinancialTowers_EN-US3881212547_1920x1080.jpg&rf=LaDigue_1920x1080.jpg&pid=hp
https://www.bing.com/th?id=OHR.LongIsland_EN-US4283514207_1920x1080.jpg&rf=LaDigue_1920x1080.jpg&pid=hp
https://www.bing.com/th?id=OHR.BeaverDam_EN-US4184266799_1920x1080.jpg&rf=LaDigue_1920x1080.jpg&pid=hp
https://www.bing.com/th?id=OHR.PicoIsland_EN-US3959411167_1920x1080.jpg&rf=LaDigue_1920x1080.jpg&pid=hp
https://www.bing.com/th?id=OHR.BeaverDam_EN-US4184266799_1920x1080.jpg&rf=LaDigue_1920x1080.jpg&pid=hp
https://www.bing.com/th?id=OHR.LongIsland_EN-US4283514207_1920x1080.jpg&rf=LaDigue_1920x1080.jpg&pid=hp
https://www.bing.com/th?id=OHR.LongIsland_EN-US4283514207_1920x1080.jpg&rf=LaDigue_1920x1080.jpg&pid=hp
https://www.bing.com/th?id=OHR.FinancialTowers_EN-US3881212547_1920x1080.jpg&rf=LaDigue_1920x1080.jpg&pid=hp
https://www.bing.com/th?id=OHR.PRNLCavern_EN-US7693319589_1920x1080.jpg&rf=LaDigue_1920x1080.jpg&pid=hp
https://www.bing.com/th?id=OHR.FinancialTowers_EN-US3881212547_1920x1080.jpg&rf=LaDigue_1920x1080.jpg&pid=hp
https://www.bing.com/th?id=OHR.BeaverDam_EN-US4184266799_1920x1080.jpg&rf=LaDigue_1920x1080.jpg&pid=hp
https://www.bing.com/th?id=OHR.PicoIsland_EN-US3959411167_1920x1080.jpg&rf=LaDigue_1920x1080.jpg&pid=hp
https://www.bing.com/th?id=OHR.FinancialTowers_EN-US3881212547_1920x1080.jpg&rf=LaDigue_1920x1080.jpg&pid=hp

I only want a single link from the above list also link should be randomize

Saksham Kushwaha
  • 274
  • 1
  • 18

1 Answers1

1

Use img=random.choice(images) out of the for loop.

images =[]
for img in soup.findAll('img'):
    images.append(img.get('src'))

img=random.choice(images)    
print(img)
Osadhi Virochana
  • 1,294
  • 2
  • 11
  • 21