programing tip

iPython 출력에 HTML을 포함시키는 방법은 무엇입니까?

itbloger 2020. 7. 10. 08:07
반응형

iPython 출력에 HTML을 포함시키는 방법은 무엇입니까?


렌더링 된 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>'))

트릭은 "디스플레이"로도 랩핑하는 것입니다.

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


얼마 전 Jupyter Notebooks는 HTML 컨텐츠에서 JavaScript를 제거하기 시작했습니다 [ # 3118 ]. 다음은 두 가지 해결책입니다.

로컬 HTML 제공

페이지에 JavaScript가 포함 된 HTML 페이지를 지금 포함 시키려면 가장 쉬운 방법은 HTML 파일을 노트북이있는 디렉토리에 저장 한 후 다음과 같이 HTML을로드하는 것입니다.

from IPython.display import IFrame

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

원격 HTML 제공

호스팅 된 솔루션을 선호하는 경우 S3의 HTML 페이지를 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 _reper_html_(self): ...인스턴스의 사용자 정의 HTML 표현을 작성하는 데 사용할 수 있습니다.

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

o = Foo()
o

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

안녕하세요 세계 !

자세한 내용은 IPython의 docs를 참조하십시오 .

고급 예 :

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을 확장 하면 필요한 경우 displayand 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

좀 더 인쇄 된 텍스트 ...

단락 텍스트는 여기에 ...


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

반응형