0

I am trying to create a script which scrapes a website for phrases which gets saved to a list and then displayed in a randomized manner. Here's the code-

from bs4 import BeautifulSoup
import requests
import random

url = 'https://www.phrases.org.uk/meanings/phrases-and-sayings-list.html'
page = requests.get(url)
soup = BeautifulSoup(page.content, 'html.parser')

for phrase in soup.find_all(class_='phrase-list'):
    phrase_text = phrase.text
    print(phrase_text)

This shows up the entire list of phrases that are scraped. How can I randomly show one phrase from the list of all phrases?

user4157124
  • 2,809
  • 13
  • 27
  • 42
Phoenix
  • 3
  • 2
  • Use `random.choice` if you just want to show a single element, `random.sample` for multiple unique random elements, or `random.shuffle` if you want to scramble the entire list. – tobias_k Apr 14 '18 at 13:04
  • Also, [Shuffling a list of objects](https://stackoverflow.com/questions/976882/shuffling-a-list-of-objects) – Keyur Potdar Apr 14 '18 at 13:12

2 Answers2

0

Use random.choice

from bs4 import BeautifulSoup
import requests
import random

url = 'https://www.phrases.org.uk/meanings/phrases-and-sayings-list.html'
page = requests.get(url)
soup = BeautifulSoup(page.content, 'html.parser')


lst = []
for phrase in soup.find_all(class_='phrase-list'):
    phrase_text = phrase.text
    lst.append(phrase_text)

random.choice(lst)

Output

'I have not slept one wink'
pythonic833
  • 3,054
  • 1
  • 12
  • 27
0

You're better off storing the phrases as a list and then using random.shuffle().

from bs4 import BeautifulSoup
import requests
import random

url = 'https://www.phrases.org.uk/meanings/phrases-and-sayings-list.html'
page = requests.get(url)
soup = BeautifulSoup(page.content, 'html.parser')

all_phrases = []

for phrase in soup.find_all(class_='phrase-list'):
    all_phrases.append(phrase.text)

random.shuffle(all_phrases)  # Replaces the list with a shuffled list

for phrase in all_phrases:
    print(phrase)
Robert Seaman
  • 2,432
  • 15
  • 18