Jestem nowy w skrobaniu internetowej Niewiele o tym nie wiem. Zrobiłem trochę programu, który pobiera losowy link obrazu ze strony internetowej, ale otrzymuję listę linków, więc nie dostaję jednego linku

Oto mój kod

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)

Oto wyjście

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

Chcę tylko pojedynczy link z powyższej listy, również należy randomizować

1
Saksham Kushwaha 6 wrzesień 2020, 11:57

1 odpowiedź

Najlepsza odpowiedź

Użyj img=random.choice(images) z pętli.

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

img=random.choice(images)    
print(img)
1
Osadhi Virochana 6 wrzesień 2020, 09:06