Created
March 26, 2023 07:06
-
-
Save reefwing/7c18b6b5a95ce9bc5a7a1b4dbe80c5b3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests | |
from bs4 import BeautifulSoup | |
import random | |
# Send GET request to Quotes to Scrape website | |
base_url = 'http://quotes.toscrape.com/page/{}/' | |
page_number = 1 | |
quotes = [] | |
while True: | |
url = base_url.format(page_number) | |
response = requests.get(url) | |
# Stop the loop if the page doesn't exist | |
if response.status_code != 200: | |
break | |
# Use BeautifulSoup to parse the HTML content of the response | |
soup = BeautifulSoup(response.content, 'html.parser') | |
# Find all the quote text elements on the page | |
quote_elements = soup.find_all('span', class_='text') | |
# Extract the text content of each quote element and add it to the list of quotes | |
quotes += [element.text.strip() for element in quote_elements] | |
# Move on to the next page | |
page_number += 1 | |
# Pick a random quote from the list of quotes | |
random_quote = random.choice(quotes) | |
# Print the random quote | |
print(random_quote) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment