programing

HTML을 IPython 출력에 삽입하려면 어떻게 해야 합니까?

copysource 2022. 10. 21. 22:27
반응형

HTML을 IPython 출력에 삽입하려면 어떻게 해야 합니까?

렌더링된 HTML 출력을 IPython 출력에 포함시킬 수 있습니까?

한 가지 방법은

from IPython.core.display import HTML
HTML('<a href="http://example.com">link</a>')

또는 (IPython 멀티라인 셀에일리어스)

%%html
<a href="http://example.com">link</a>

포맷된 링크가 반환되지만

  1. 이 링크는 콘솔에서 웹 페이지 자체를 사용하여 브라우저를 열지 않습니다.그러나 IPython 노트북은 정직한 렌더링을 지원합니다.
  2. 어떻게 렌더링해야 할지 모르겠어요.HTML()예를 들어 리스트 내의 오브젝트 또는pandas인쇄된 표할수있습니다df.to_html()단, 셀 내부에 링크를 만들지 않습니다.
  3. 이 출력은 PyCharm Python 콘솔에서는 인터랙티브하지 않습니다(QT가 아니기 때문에).

어떻게 하면 이러한 단점을 극복하고 IPython 출력을 좀 더 인터랙티브하게 할 수 있을까요?

이 방법이 효과가 있는 것 같습니다.

from IPython.core.display import display, HTML
display(HTML('<h1>Hello, world!</h1>'))

요령은 그것을 포장하는 것이다.display뿐만 아니라.

출처 : http://python.6.x6.nabble.com/Printing-HTML-within-IPython-Notebook-IPython-specific-prettyprint-tp5016624p5016631.html

편집:

from IPython.display import display, HTML

피하려면:

DeprecationWarning: Importing display from IPython.core.display is 
deprecated since IPython 7.14, please import from IPython display

얼마 전 Jupyter 노트북은 HTML 콘텐츠에서 JavaScript를 삭제하기 시작했습니다[#318].다음은 두 가지 해결 방법입니다.

로컬 HTML 서비스

지금 바로 페이지에 JavaScript를 포함한 HTML 페이지를 삽입하려면 HTML 파일을 노트북으로 디렉토리에 저장한 후 다음과 같이 HTML을 로드하는 것이 가장 쉽습니다.

from IPython.display import IFrame

IFrame(src='./nice.html', width=700, height=600)

리모트 HTML 서비스

호스트된 솔루션을 선호하는 경우 HTML 페이지를 S3의 Amazon Web Services "버킷"에 업로드하고 버킷 호스트를 정적 웹 사이트로 만들기 위해 해당 버킷의 설정을 변경한 다음 노트북의 Iframe 구성 요소를 사용할 수 있습니다.

from IPython.display import IFrame

IFrame(src='https://s3.amazonaws.com/duhaime/blog/visualizations/isolation-forests.html', width=700, height=600)

다른 웹 페이지와 마찬가지로 HTML 콘텐츠와 JavaScript를 iframe으로 렌더링합니다.

<iframe src='https://s3.amazonaws.com/duhaime/blog/visualizations/isolation-forests.html', width=700, height=600></iframe>

연관된:클래스를 만드는 동안def _repr_html_(self): ...는 인스턴스 커스텀HTML 표현을 작성하기 위해 사용할 수 있습니다.

class Foo:
    def _repr_html_(self):
        return "Hello <b>World</b>!"

o = Foo()
o

다음과 같이 렌더링합니다.

헬로 월드!

상세한 것에 대하여는, IPython 문서를 참조해 주세요.

고급 예:

from html import escape # Python 3 only :-)

class Todo:
    def __init__(self):
        self.items = []

    def add(self, text, completed):
        self.items.append({'text': text, 'completed': completed})

    def _repr_html_(self):
        return "<ol>{}</ol>".format("".join("<li>{} {}</li>".format(
            "☑" if item['completed'] else "☐",
            escape(item['text'])
        ) for item in self.items))

my_todo = Todo()
my_todo.add("Buy milk", False)
my_todo.add("Do homework", False)
my_todo.add("Play video games", True)

my_todo

렌더링:

  1. ②우유 구입
  2. ①숙제하다
  3. ☑ 비디오 게임 재생

위의 @Harmon에서 확장하면display그리고.print함께 진술...필요하시면 말씀하세요.또는 HTML 전체를 하나의 문자열로 포맷하고 디스플레이를 사용하는 것이 더 쉬울 수 있습니다.어느 쪽이든, 좋은 특징이야.

display(HTML('<h1>Hello, world!</h1>'))
print("Here's a link:")
display(HTML("<a href='http://www.google.com' target='_blank'>www.google.com</a>"))
print("some more printed text ...")
display(HTML('<p>Paragraph text here ...</p>'))

다음과 같이 출력합니다.


안녕, 세상아!

다음은 링크입니다.

www.google.com

좀 더 인쇄된 텍스트...

여기 단락 텍스트...


첫 번째 코드는 다음과 같습니다.

from random import choices

def random_name(length=6):
    return "".join(choices("abcdefghijklmnopqrstuvwxyz", k=length))
# ---

from IPython.display import IFrame, display, HTML
import tempfile
from os import unlink

def display_html_to_frame(html, width=600, height=600):
    name = f"temp_{random_name()}.html"
    with open(name, "w") as f:
        print(html, file=f)
    display(IFrame(name, width, height), metadata=dict(isolated=True))
    # unlink(name)
    
def display_html_inline(html):
    display(HTML(html, metadata=dict(isolated=True)))

h="<html><b>Hello</b></html>"    
display_html_to_iframe(h)
display_html_inline(h)

간단한 메모:

  • 일반적으로 간단한 항목에는 인라인 HTML만 사용할 수 있습니다.대규모 JavaScript 시각화 프레임워크와 같은 프레임워크를 렌더링하는 경우 IFrame을 사용해야 할 수 있습니다.Jupyter는 임의의 HTML을 내장하지 않고 브라우저에서 실행하기에 충분히 어렵다.
  • 한 파라미터 " " " " "metadata=dict(isolated=True)는 오래된 매뉴얼에 나타나 있듯이 IFrame 내의 결과를 분리하지 않습니다.이 때문에clear-fix모든 것을 리셋하는 것을 막을 수 있습니다.플래그는 더 이상 문서화되지 않습니다. 정도 쓸 수 display: grid이치노
  • ★★★★★★★★★★★★★★★★★.IFrame솔루션이 임시 파일에 씁니다.여기서 설명하는 대로 데이터 URI를 사용할 수 있지만 출력 디버깅이 어렵습니다.주피터IFrame는 a를 .data ★★★★★★★★★★★★★★★★★」srcdoc여하하다
  • tempfile은 다른할 수 모듈 작성은 다른 프로세스와 공유할 수 없습니다.random_name().
  • IFrame이 포함된 HTML 클래스를 사용하면 경고가 표시됩니다.이것은 세션당 1회만 가능합니다.
  • 하시면 됩니다.HTML('Hello, <b>world</b>')셀의 최상위 레벨과 그 반환값이 렌더링됩니다.에서 " " "를 사용합니다.display(HTML(...)), 「」, 「」, 「」, 「」를 시킬 수도 .display ★★★★★★★★★★★★★★★★★」print자유롭게 통화할 수 있습니다.
  • 이상하게도 IFrames는 인라인 HTML보다 약간 더 들여쓰기 됩니다.

이것을 루프내에서 실시하려면 , 다음의 조작을 실시합니다.

display(HTML("".join([f"<a href='{url}'>{url}</a></br>" for url in urls])))

기본적으로 html 텍스트를 루프에 만들고 display(HTML) 구성을 사용하여 문자열 전체를 HTML로 표시합니다.

언급URL : https://stackoverflow.com/questions/25698448/how-to-embed-html-into-ipython-output

반응형