2
\$\begingroup\$

Here is my code that I recently made (I am a beginner). I used BeautifulSoup and Requests to get the data of this website. Please read over my code and tell me how to improve it. Thanks.

import random
import time
from os import system
import keyring
from bs4 import BeautifulSoup
import requests

def getdata(url):
    headers = {
    'User-agent':
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582"}  
    r = requests.get(url, headers=headers)
    return r.text
def main():
    print('This is trivia, made by MY_NAME. Have fun!')
    print()
    while True:
        try:
            amount = int(input('How many questions would you like to answer? '))
            print()
        except ValueError:
            print()
            print('Must be a natural number.')
            print()
        else:
            if amount < 10 or amount > 145:
                print('Must be a natural number above 10 and less than 145.')
                print()
            else:
                break
    htmldata = getdata('https://www.scarymommy.com/best-trivia-questions-answers/')
    soup = BeautifulSoup(htmldata, 'html.parser')
    q = str(soup.find_all(text=True))
    questions = []
    answers = []
    for x in range(1, amount + 1):
        question_index = q.find(f'{x}. ')
        next_index = q.find(f'{x+1}. ')
        to_add = q[question_index:next_index]
        to_add = to_add.replace("', '", '')
        to_add = to_add.replace('\n', '')
        questions.append(to_add[0:-1])
    for x in range(amount):
        unsplit = questions[x]
        split = unsplit.split(' Answer: ')
        que = split[0]
        que = que.replace(f'{x+1}. ', '')
        ans = split[1]
        ans = ans.replace('.\\', '')
        ans = ans.replace('\\n', '')
        ans = ans.replace('\\', '')
        answers.append(ans)
        questions[x] = que

    music = "/Users/XIA/Desktop/Python/Projects/Trivia/Music/intro_music.wav"
    system("afplay " + music)
    hisc_nme = keyring.get_password('trivia', 'hi')
    hisc_sce = keyring.get_password('trivia', 'sc')
    print()
    print('You will answer {} questions within 15 seconds, and the faster you answer, the more point\'s you\'ll get.'.format(len(questions)))
    print('Right now, {} has the high score of {}.'.format(hisc_nme, hisc_sce))
    print('Good luck, and have fun!')
    print()
    time.sleep(1)
    while True:
        cor_count = 0
        score = 0
        count = 0
        choices = list(range(len(questions)))
        for x in range(0, len(questions)):
            quest = random.choice(choices)
            choices.remove(quest)
            start = time.time()
            answer = input(questions[quest] + ' ').lower()
            end = time.time()
            Canswer = answers[quest]
            pCanswer = Canswer
            Canswer = Canswer.lower()
            time_took = end - start
            if answer != Canswer.strip():
                print('Wrong!')
                count += 1
                print('Your current score is {}.'.format(score))
                print('The correct answer was {}.'.format(pCanswer))
                print()
                time.sleep(1)
            else:
                print('Correct!')
                cor_count += 1
                count += 1
                print('You took {} seconds.'.format(round(time_took)))
                score += 1 + round((15/(time_took)))
                print('Your current score is {}.'.format(score))
                print()
                time.sleep(1)
        print('You got {} out of {} right. Your final score is {}.'.format(cor_count, count, score))
        if int(score) > int(hisc_sce):
            print('New high score!')
            new_name = input('Enter your name to be saved as the high score: ')
            keyring.set_password('trivia', 'hi', new_name)
            keyring.set_password('trivia', 'sc', str(score))
        again = input('Play again (y/n): ')
        if again.lower() != 'y':
            print('Goodbye!')
            system('say -v Victoria Please do not be salty and rage quit.')
            break
if __name__ == '__main__':
    main()
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

Broadly: this isn't a particularly useful application of scraping. You're scraping static content. You'd be better off literally copying and pasting that content into a local, hand-generated JSON file distributed with your game (while also including copyright attribution to the original source).

Do that, split up your mega-main into several different functions, and you'll be well on your way to sanity.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.