Hướng dẫn how do you show html output on a web page in python? - làm thế nào để bạn hiển thị đầu ra html trên một trang web trong python?

Cải thiện bài viết

Lưu bài viết

Python là một trong những ngôn ngữ lập trình linh hoạt nhất. Nó nhấn mạnh khả năng đọc mã với việc sử dụng rộng rãi không gian trắng. Nó đi kèm với sự hỗ trợ của một bộ sưu tập các thư viện khổng lồ phục vụ cho các mục đích khác nhau, làm cho trải nghiệm lập trình của chúng tôi mượt mà và thú vị hơn. & NBSP;

Các chương trình Python được sử dụng cho:

  • Kết nối với cơ sở dữ liệu và thực hiện phát triển phụ trợ.
  • Làm ứng dụng web.
  • Viết kịch bản hệ thống hiệu quả.
  • Và đặc biệt là trong khoa học dữ liệu và trí tuệ nhân tạo.

Với điều này đã nói, chúng tôi hãy xem cách chúng tôi có thể sử dụng các chương trình Python để tạo các tệp HTML làm đầu ra. Điều này rất hiệu quả cho những chương trình tự động tạo các siêu liên kết và thực thể đồ họa.

Tạo tệp HTML trong Python

Chúng tôi sẽ lưu trữ các thẻ HTML trong chuỗi Python đa dòng và lưu nội dung vào một tệp mới. Tệp này sẽ được lưu với tiện ích mở rộng .html thay vì tiện ích mở rộng .txt.

Lưu ý: Chúng tôi sẽ bỏ qua Tuyên bố tiêu chuẩn! We would be omitting the standard declaration!

Python3

f

print("Helo");
0
print("Helo");
1
print("Helo");
2
print("Helo");
3
print("Helo");
4
print("Helo");
5
print("Helo");
6

print("Helo");
7
print("Helo");
0

print("Helo");
9


frame = 'This fruit is a %s'
print(frame)
-> This fruit is a %s

print(frame % 'banana')
-> This fruit is a banana

print(frame % 'pear')
-> This fruit is a pear
0

Chương trình trên sẽ tạo một tệp HTML:

Hướng dẫn how do you show html output on a web page in python? - làm thế nào để bạn hiển thị đầu ra html trên một trang web trong python?

Xem tệp nguồn HTML

Để hiển thị tệp HTML dưới dạng đầu ra Python, chúng tôi sẽ sử dụng thư viện Codecs. Thư viện này được sử dụng để mở các tệp có mã hóa nhất định. Nó có một mã hóa tham số làm cho nó khác với hàm Open in () tích hợp. & nbsp; hàm Open () không chứa bất kỳ tham số nào để chỉ định mã hóa tệp, điều mà hầu hết thời gian gây khó khăn cho việc xem các tệp không phải là ASCII mà là UTF-8.

Python3


frame = 'This fruit is a %s'
print(frame)
-> This fruit is a %s

print(frame % 'banana')
-> This fruit is a banana

print(frame % 'pear')
-> This fruit is a pear
1

frame = 'This fruit is a %s'
print(frame)
-> This fruit is a %s

print(frame % 'banana')
-> This fruit is a banana

print(frame % 'pear')
-> This fruit is a pear
2

f

print("Helo");
0
print("Helo");
1
print("Helo");
2
print("Helo");
3
print("Helo");
4
print("Helo");
5
print("Helo");
6

print("Helo");
7
print("Helo");
0

print("Helo");
9


frame = 'This fruit is a %s'
print(frame)
-> This fruit is a %s

print(frame % 'banana')
-> This fruit is a banana

print(frame % 'pear')
-> This fruit is a pear
0

Chương trình trên sẽ tạo một tệp HTML:

# Given a URL, return string of lowercase text from page.

def webPageToText(url):
    import urllib.request, urllib.error, urllib.parse
    response = urllib.request.urlopen(url)
    html = response.read().decode('UTF-8')
    text = stripTags(html).lower()
    return text
6
print("Helo");
2

frame2 = 'These are %s, those are %s'
print(frame2)
-> These are %s, those are %s

print(frame2 % ('bananas', 'pears'))
-> These are bananas, those are pears
5
# Given a URL, return string of lowercase text from page.

def webPageToText(url):
    import urllib.request, urllib.error, urllib.parse
    response = urllib.request.urlopen(url)
    html = response.read().decode('UTF-8')
    text = stripTags(html).lower()
    return text
9

Output:

Hướng dẫn how do you show html output on a web page in python? - làm thế nào để bạn hiển thị đầu ra html trên một trang web trong python?

Xem tệp nguồn HTML

Để hiển thị tệp HTML dưới dạng đầu ra Python, chúng tôi sẽ sử dụng thư viện Codecs. Thư viện này được sử dụng để mở các tệp có mã hóa nhất định. Nó có một mã hóa tham số làm cho nó khác với hàm Open in () tích hợp. & nbsp; hàm Open () không chứa bất kỳ tham số nào để chỉ định mã hóa tệp, điều mà hầu hết thời gian gây khó khăn cho việc xem các tệp không phải là ASCII mà là UTF-8.

Python3


frame = 'This fruit is a %s'
print(frame)
-> This fruit is a %s

print(frame % 'banana')
-> This fruit is a banana

print(frame % 'pear')
-> This fruit is a pear
1

frame = 'This fruit is a %s'
print(frame)
-> This fruit is a %s

print(frame % 'banana')
-> This fruit is a banana

print(frame % 'pear')
-> This fruit is a pear
2

# Given name of calling program, a url and a string to wrap,
# output string in html body with basic metadata and open in Firefox tab.

def wrapStringInHTMLMac(program, url, body):
    import datetime
    from webbrowser import open_new_tab

    now = datetime.datetime.today().strftime("%Y%m%d-%H%M%S")
    filename = program + '.html'
    f = open(filename,'w')

    wrapper = """<html>
    <head>
    <title>%s output - %s</title>
    </head>
    <body><p>URL: <a href=\"%s\">%s</a></p><p>%s</p></body>
    </html>"""

    whole = wrapper % (program, now, url, url, body)
    f.write(whole)
    f.close()

    #Change the filepath variable below to match the location of your directory
    filename = 'file:///Users/username/Desktop/programming-historian/' + filename

    open_new_tab(filename)
2
print("Helo");
1
print("Helo");
2
print("Helo");
3
# Given name of calling program, a url and a string to wrap,
# output string in html body with basic metadata and open in Firefox tab.

def wrapStringInHTMLMac(program, url, body):
    import datetime
    from webbrowser import open_new_tab

    now = datetime.datetime.today().strftime("%Y%m%d-%H%M%S")
    filename = program + '.html'
    f = open(filename,'w')

    wrapper = """<html>
    <head>
    <title>%s output - %s</title>
    </head>
    <body><p>URL: <a href=\"%s\">%s</a></p><p>%s</p></body>
    </html>"""

    whole = wrapper % (program, now, url, url, body)
    f.write(whole)
    f.close()

    #Change the filepath variable below to match the location of your directory
    filename = 'file:///Users/username/Desktop/programming-historian/' + filename

    open_new_tab(filename)
6

Output:

True

Hướng dẫn how do you show html output on a web page in python? - làm thế nào để bạn hiển thị đầu ra html trên một trang web trong python?


Helo, tôi là một người mới; Tôi biết tôi có thể sử dụng

# Given name of calling program, a url and a string to wrap,
# output string in html body with basic metadata and open in Firefox tab.

def wrapStringInHTMLMac(program, url, body):
    import datetime
    from webbrowser import open_new_tab

    now = datetime.datetime.today().strftime("%Y%m%d-%H%M%S")
    filename = program + '.html'
    f = open(filename,'w')

    wrapper = """<html>
    <head>
    <title>%s output - %s</title>
    </head>
    <body><p>URL: <a href=\"%s\">%s</a></p><p>%s</p></body>
    </html>"""

    whole = wrapper % (program, now, url, url, body)
    f.write(whole)
    f.close()

    #Change the filepath variable below to match the location of your directory
    filename = 'file:///Users/username/Desktop/programming-historian/' + filename

    open_new_tab(filename)
7 Đây là để hiển thị một văn bản trên trang web bằng cách sử dụng
# Given name of calling program, a url and a string to wrap,
# output string in html body with basic metadata and open in Firefox tab.

def wrapStringInHTMLMac(program, url, body):
    import datetime
    from webbrowser import open_new_tab

    now = datetime.datetime.today().strftime("%Y%m%d-%H%M%S")
    filename = program + '.html'
    f = open(filename,'w')

    wrapper = """<html>
    <head>
    <title>%s output - %s</title>
    </head>
    <body><p>URL: <a href=\"%s\">%s</a></p><p>%s</p></body>
    </html>"""

    whole = wrapper % (program, now, url, url, body)
    f.write(whole)
    f.close()

    #Change the filepath variable below to match the location of your directory
    filename = 'file:///Users/username/Desktop/programming-historian/' + filename

    open_new_tab(filename)
8 nhưng tôi có tên tệp
# Given name of calling program, a url and a string to wrap,
# output string in html body with basic metadata and open in Firefox tab.

def wrapStringInHTMLMac(program, url, body):
    import datetime
    from webbrowser import open_new_tab

    now = datetime.datetime.today().strftime("%Y%m%d-%H%M%S")
    filename = program + '.html'
    f = open(filename,'w')

    wrapper = """<html>
    <head>
    <title>%s output - %s</title>
    </head>
    <body><p>URL: <a href=\"%s\">%s</a></p><p>%s</p></body>
    </html>"""

    whole = wrapper % (program, now, url, url, body)
    f.write(whole)
    f.close()

    #Change the filepath variable below to match the location of your directory
    filename = 'file:///Users/username/Desktop/programming-historian/' + filename

    open_new_tab(filename)
9 và nó có mã

print("Helo");

Vì vậy, bây giờ tôi phải hiển thị nó trên màn hình này, vậy làm thế nào tôi có thể làm điều đó 🙂

Hướng dẫn how do you show html output on a web page in python? - làm thế nào để bạn hiển thị đầu ra html trên một trang web trong python?

Hỏi ngày 19 tháng 10 năm 2021 lúc 4:04Oct 19, 2021 at 4:04

Hướng dẫn how do you show html output on a web page in python? - làm thế nào để bạn hiển thị đầu ra html trên một trang web trong python?

1

1 câu trả lời

Bạn có thể làm theo hướng dẫn này để tạo một máy chủ web cơ bản sẽ hiển thị bất kỳ HTML nào bạn muốn nếu đó là những gì bạn đang tìm kiếm.

Đã trả lời ngày 19 tháng 10 năm 2021 lúc 4:17Oct 19, 2021 at 4:17

Admin_WhoAdmin_WhoAdmin_Who

2953 Huy hiệu bạc12 Huy hiệu Đồng3 silver badges12 bronze badges

Nội dung

  • Mục tiêu bài học
  • Các tệp cần thiết cho bài học này
  • Xây dựng trình bao bọc HTML
  • metadata
  • Định dạng chuỗi Python
  • Tệp dữ liệu tự ghi chép
    • Hướng dẫn Mac
    • Hướng dẫn Windows
  • Để tất cả chúng cùng nhau
    • Bài đọc đề xuất
    • Đồng bộ hóa mã

Mục tiêu bài học

Các tệp cần thiết cho bài học này

Xây dựng trình bao bọc HTML

Các tệp cần thiết cho bài học này

  • # Given name of calling program, a url and a string to wrap,
    # output string in html body with basic metadata
    # and open in Firefox tab.
    
    def wrapStringInHTMLWindows(program, url, body):
        import datetime
        from webbrowser import open_new_tab
    
        now = datetime.datetime.today().strftime("%Y%m%d-%H%M%S")
    
        filename = program + '.html'
        f = open(filename,'w')
    
        wrapper = """<html>
        <head>
        <title>%s output - %s</title>
        </head>
        <body><p>URL: <a href=\"%s\">%s</a></p><p>%s</p></body>
        </html>"""
    
        whole = wrapper % (program, now, url, url, body)
        f.write(whole)
        f.close()
    
        open_new_tab(filename)
    
    0

Xây dựng trình bao bọc HTML

Xây dựng trình bao bọc HTML

metadata

Định dạng chuỗi Python

Tệp dữ liệu tự ghi chép

Định dạng chuỗi Python

Tệp dữ liệu tự ghi chép


frame = 'This fruit is a %s'
print(frame)
-> This fruit is a %s

print(frame % 'banana')
-> This fruit is a banana

print(frame % 'pear')
-> This fruit is a pear

Hướng dẫn Mac


frame2 = 'These are %s, those are %s'
print(frame2)
-> These are %s, those are %s

print(frame2 % ('bananas', 'pears'))
-> These are bananas, those are pears

Hướng dẫn Windows

Tệp dữ liệu tự ghi chép

Hướng dẫn Mac

# Given a URL, return string of lowercase text from page.

def webPageToText(url):
    import urllib.request, urllib.error, urllib.parse
    response = urllib.request.urlopen(url)
    html = response.read().decode('UTF-8')
    text = stripTags(html).lower()
    return text

Hướng dẫn Windows

Hướng dẫn Mac

Nếu bạn đang sử dụng máy Mac, hãy đảm bảo bạn bao gồm đường dẫn tệp thích hợp trong biến tên tệp trên dòng cuối cùng thứ 2 để phản ánh nơi bạn lưu tệp của mình.

# Given name of calling program, a url and a string to wrap,
# output string in html body with basic metadata and open in Firefox tab.

def wrapStringInHTMLMac(program, url, body):
    import datetime
    from webbrowser import open_new_tab

    now = datetime.datetime.today().strftime("%Y%m%d-%H%M%S")
    filename = program + '.html'
    f = open(filename,'w')

    wrapper = """<html>
    <head>
    <title>%s output - %s</title>
    </head>
    <body><p>URL: <a href=\"%s\">%s</a></p><p>%s</p></body>
    </html>"""

    whole = wrapper % (program, now, url, url, body)
    f.write(whole)
    f.close()

    #Change the filepath variable below to match the location of your directory
    filename = 'file:///Users/username/Desktop/programming-historian/' + filename

    open_new_tab(filename)

Hướng dẫn Windows

# Given name of calling program, a url and a string to wrap,
# output string in html body with basic metadata
# and open in Firefox tab.

def wrapStringInHTMLWindows(program, url, body):
    import datetime
    from webbrowser import open_new_tab

    now = datetime.datetime.today().strftime("%Y%m%d-%H%M%S")

    filename = program + '.html'
    f = open(filename,'w')

    wrapper = """<html>
    <head>
    <title>%s output - %s</title>
    </head>
    <body><p>URL: <a href=\"%s\">%s</a></p><p>%s</p></body>
    </html>"""

    whole = wrapper % (program, now, url, url, body)
    f.write(whole)
    f.close()

    open_new_tab(filename)

***

Lưu ý rằng chức năng này sử dụng toán tử định dạng chuỗi mà chúng ta vừa học. Nếu bạn vẫn gặp rắc rối với ý tưởng này, hãy xem tệp HTML mở trong tab Firefox mới của bạn và bạn sẽ thấy cách thức hoạt động của nó. Nếu bạn vẫn bị mắc kẹt, hãy xem

URL: http://www.oldbaileyonline.org/browse.jsp?id=t17800628-33&div=t17800628-33

Trong tệp HTML và truy tìm lại cách chương trình biết đặt giá trị URL ở đó.

Hàm này cũng gọi thư viện Python

# Given name of calling program, a url and a string to wrap,
# output string in html body with basic metadata
# and open in Firefox tab.

def wrapStringInHTMLWindows(program, url, body):
    import datetime
    from webbrowser import open_new_tab

    now = datetime.datetime.today().strftime("%Y%m%d-%H%M%S")

    filename = program + '.html'
    f = open(filename,'w')

    wrapper = """<html>
    <head>
    <title>%s output - %s</title>
    </head>
    <body><p>URL: <a href=\"%s\">%s</a></p><p>%s</p></body>
    </html>"""

    whole = wrapper % (program, now, url, url, body)
    f.write(whole)
    f.close()

    open_new_tab(filename)
6 để xác định thời gian và ngày hiện tại. Giống như toán tử định dạng chuỗi
# Given name of calling program, a url and a string to wrap,
# output string in html body with basic metadata
# and open in Firefox tab.

def wrapStringInHTMLWindows(program, url, body):
    import datetime
    from webbrowser import open_new_tab

    now = datetime.datetime.today().strftime("%Y%m%d-%H%M%S")

    filename = program + '.html'
    f = open(filename,'w')

    wrapper = """<html>
    <head>
    <title>%s output - %s</title>
    </head>
    <body><p>URL: <a href=\"%s\">%s</a></p><p>%s</p></body>
    </html>"""

    whole = wrapper % (program, now, url, url, body)
    f.write(whole)
    f.close()

    open_new_tab(filename)
1, thư viện này sử dụng
# Given name of calling program, a url and a string to wrap,
# output string in html body with basic metadata
# and open in Firefox tab.

def wrapStringInHTMLWindows(program, url, body):
    import datetime
    from webbrowser import open_new_tab

    now = datetime.datetime.today().strftime("%Y%m%d-%H%M%S")

    filename = program + '.html'
    f = open(filename,'w')

    wrapper = """<html>
    <head>
    <title>%s output - %s</title>
    </head>
    <body><p>URL: <a href=\"%s\">%s</a></p><p>%s</p></body>
    </html>"""

    whole = wrapper % (program, now, url, url, body)
    f.write(whole)
    f.close()

    open_new_tab(filename)
8 làm thay thế cho các giá trị. Trong trường hợp này,
# Given name of calling program, a url and a string to wrap,
# output string in html body with basic metadata
# and open in Firefox tab.

def wrapStringInHTMLWindows(program, url, body):
    import datetime
    from webbrowser import open_new_tab

    now = datetime.datetime.today().strftime("%Y%m%d-%H%M%S")

    filename = program + '.html'
    f = open(filename,'w')

    wrapper = """<html>
    <head>
    <title>%s output - %s</title>
    </head>
    <body><p>URL: <a href=\"%s\">%s</a></p><p>%s</p></body>
    </html>"""

    whole = wrapper % (program, now, url, url, body)
    f.write(whole)
    f.close()

    open_new_tab(filename)
9 đại diện cho năm, tháng, ngày, giờ, phút và thứ hai tương ứng. Không giống như
# Given name of calling program, a url and a string to wrap,
# output string in html body with basic metadata
# and open in Firefox tab.

def wrapStringInHTMLWindows(program, url, body):
    import datetime
    from webbrowser import open_new_tab

    now = datetime.datetime.today().strftime("%Y%m%d-%H%M%S")

    filename = program + '.html'
    f = open(filename,'w')

    wrapper = """<html>
    <head>
    <title>%s output - %s</title>
    </head>
    <body><p>URL: <a href=\"%s\">%s</a></p><p>%s</p></body>
    </html>"""

    whole = wrapper % (program, now, url, url, body)
    f.write(whole)
    f.close()

    open_new_tab(filename)
1, chương trình sẽ xác định giá trị của các biến này cho bạn bằng đồng hồ máy tính của bạn. Điều quan trọng là phải nhận ra sự khác biệt này.

Siêu dữ liệu ngày này, cùng với tên của chương trình được gọi là hàm, được lưu trữ trong thẻ tiêu đề HTML. Tệp HTML được tạo có cùng tên với chương trình Python tạo ra nó, nhưng với tiện ích mở rộng

URL: http://www.oldbaileyonline.org/browse.jsp?id=t17800628-33&div=t17800628-33
1 thay vì tệp
URL: http://www.oldbaileyonline.org/browse.jsp?id=t17800628-33&div=t17800628-33
2.

Để tất cả chúng cùng nhau

Bây giờ chúng tôi có thể tạo một phiên bản khác của chương trình của chúng tôi để tính toán tần số. Thay vì gửi đầu ra của nó đến một tệp văn bản hoặc cửa sổ đầu ra, nó sẽ gửi đầu ra đến tệp HTML được mở trong tab Firefox mới. Từ đó, đầu ra của chương trình có thể được thêm dễ dàng như các mục thư mục cho Zotero. Nhập hoặc sao chép mã sau vào trình soạn thảo văn bản của bạn, lưu nó dưới dạng

URL: http://www.oldbaileyonline.org/browse.jsp?id=t17800628-33&div=t17800628-33
3 và thực thi nó, để xác nhận rằng nó hoạt động như mong đợi.

Sử dụng obo.wrapstringinhtmlmac () hoặc obo.wrapstringinhtmlwindows () khi phù hợp với hệ thống của bạn.

# html-to-freq-3.py
import obo

# create sorted dictionary of word-frequency pairs
url = 'http://www.oldbaileyonline.org/browse.jsp?id=t17800628-33&div=t17800628-33'
text = obo.webPageToText(url)
fullwordlist = obo.stripNonAlphaNum(text)
wordlist = obo.removeStopwords(fullwordlist, obo.stopwords)
dictionary = obo.wordListToFreqDict(wordlist)
sorteddict = obo.sortFreqDict(dictionary)

# compile dictionary into string and wrap with HTML
outstring = ""
for s in sorteddict:
    outstring += str(s)
    outstring += "<br />"
obo.wrapStringInHTMLMac("html-to-freq-3", url, outstring)

Lưu ý rằng chúng tôi đã xen kẽ các cặp tần số từ với thẻ HTML Break

URL: http://www.oldbaileyonline.org/browse.jsp?id=t17800628-33&div=t17800628-33
4, hoạt động như một dòng mới. Nếu mọi việc suôn sẻ, bạn sẽ thấy cùng một tần số từ mà bạn đã tính toán trong phần cuối, lần này trong cửa sổ trình duyệt của bạn.

Bài đọc đề xuất

  • Lutz, học Python
    • Đọc lại và xem xét chs. 1-17

Đồng bộ hóa mã

Để làm theo cùng với các bài học trong tương lai, điều quan trọng là bạn có các tệp và chương trình phù hợp trong thư mục lập trình của bạn. Ở cuối mỗi chương, bạn có thể tải xuống tệp ZIP lập trình-Historian Hitming-Historian để đảm bảo bạn có mã chính xác. Nếu bạn đang theo dõi cùng với phiên bản MAC/Linux, bạn có thể phải mở tệp

# Given name of calling program, a url and a string to wrap,
# output string in html body with basic metadata
# and open in Firefox tab.

def wrapStringInHTMLWindows(program, url, body):
    import datetime
    from webbrowser import open_new_tab

    now = datetime.datetime.today().strftime("%Y%m%d-%H%M%S")

    filename = program + '.html'
    f = open(filename,'w')

    wrapper = """<html>
    <head>
    <title>%s output - %s</title>
    </head>
    <body><p>URL: <a href=\"%s\">%s</a></p><p>%s</p></body>
    </html>"""

    whole = wrapper % (program, now, url, url, body)
    f.write(whole)
    f.close()

    open_new_tab(filename)
0 và thay đổi tệp: /// người dùng/tên người dùng/máy tính để bàn/lập trình-historian/Hồi sang đường dẫn đến thư mục trên máy tính của riêng bạn.

  • Python-irssons7.zip Zip Sync