파이썬/파이썬(python) 중급

[34-1 파이썬] 퀴즈 API, HTML unescape, HTML escape, HTML 개체, HTML 변환기, HTML 파이썬 변환

Olivia-BlackCherry 2022. 9. 26. 17:11

오늘은 Open Trivia DB 사이트에서 퀴즈 문제를  API로 받아, 

파이썬 코드를 실행할 때마다 새롭게 문제가 업데이트 되는

파이썬 코드를 작성해본다.

 

1. 퀴즈 문제 API 받기

https://opentdb.com/api_config.php

 

Open Trivia DB

Free to use, user-contributed trivia questions!

opentdb.com

 

해당당 조건으로 생성된 API URL

https://opentdb.com/api.php?amount=10&category=25&difficulty=easy&type=boolean

 

파라미터를 수정하기 위해서, 위의 URL에서 ? 앞의 URL만 가져온다.

https://opentdb.com/api.php?amount=10 

 

그러면 파라미터로 amount, category, difficulty, type을 넣을 수 있다는 것을 알 수 있는데

이번에는 amount, type 파라미터만 수정해보도록 하겠다.

import requests
parameters= {
    "amount": 10,
    "type": "boolean"
}
response = requests.get("https://opentdb.com/api.php", params= parameters)

response.raise_for_status()
data = response.json()
question_data =data["results"]
print(question_data)

이렇게 하면, 

매번 코드가 실행될 때마다 

다른 10개의 문제(T/F답을 갖는)가 생성 된다. 

 

 

2.  HTML 개체(Escape HTML)

그런데 문제가 있다.

question을 출력해보면, 이상한 외계어가 있다. 

이 부분을 삭제해야 제대로 question을 읽을 수 있다.

'question': 'There aren't any live-action clones in "Star Wars: Episode III - Revenge of the Sith".'

 

이러한 외계어는 HTML 개체라는 것이다.

특정 문자(< > " ' & 등)는 생긴 그대로 받아지는 것이 아니라,

HTML의 형태로 바뀌어 받아진다는 것이다.

출처: w3schools.com

 

 

3. HTML 개체 변환(Unescape HTML)

1) 무료 변환기 사이트 이용

무료 변환기 사이트 --> 클릭

unescape HTML을 누르면 아래와 같이 변환되어 나온다.

 

2) 파이썬 코드로 변환

import html
html.unescape()

파이썬 코드로 HTML을 원래 글자로 변환하고자 한다면

먼저 html 모듈을 import하고

unescape(바꿀내용)함수를 쓴다.

import requests
import html

parameters= {
    "amount": 10,
    "type": "boolean"
}
response = requests.get("https://opentdb.com/api.php", params= parameters)
response.raise_for_status()
data = response.json()

question_data =data["results"]

#html.unescape(바꿀내용)
for question in question_data:
    question['question'] = html.unescape(question['question'])
    print(question['question'])

>>Hippopotomonstrosesquippedaliophobia is the irrational fear of long words.
Type 1 diabetes is a result of the liver working improperly.
The 2016 United States Presidential Election is the first time Hillary Clinton has run for President.
The Olympics tennis court is a giant green screen.
Throughout the entirety of "Dragon Ball Z", Goku only kills two characters: a miniboss named Yakon and Kid Buu.
The Platypus is a mammal.
"Cube", "Cube 2: Hypercube" and "Cube Zero" were directed by the same person.