這段代碼對我不起作用
我想知道一種在沒有tkinterhtml的情況下使用 python 呈現 html 的方法
加載時google.com,我收到錯誤:
Exception in Tkinter callback
Traceback (most recent call last):
File "c:\python scripts\project\file.py", line 10, in search
html = htmlBytes.decode("utf8")
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe7 in position 10955: invalid continuation byte
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 1921, in __call__
return self.func(*args)
File "c:\python scripts\project\file.py", line 12, in search
html = htmlBytes.decode("utf16")
UnicodeDecodeError: 'utf-16-le' codec can't decode byte 0x3e in position 14624: truncated data
我正在為一個專案作業,并正在使用import關鍵字啟動代碼。我的代碼不起作用并在搜索功能完成后關閉視窗。
import urllib.request
import tkinter
from tkinterhtml import HtmlFrame
def search():
url = urlInput.get()
page = urllib.request.urlopen(url)
htmlBytes = page.read()
try:
html = htmlBytes.decode("utf8")
except:
html = htmlBytes.decode("utf16")
frame.set_content(html)
page.close()
screen = tkinter.Tk()
screen.geometry("700x700")
frame = HtmlFrame(screen, horizontal_scrollbar="auto")
urlInput = tkinter.Entry(screen)
urlInput.grid(column=0,row=0,columnspan=10,rowspan=4,sticky="news")
searchBtn = tkinter.Button(screen,text="search",command=search)
searchBtn.grid(row=0,column=11,sticky="news")
screen.mainloop()
uj5u.com熱心網友回復:
tkinter 沒有呈現 HTML 的能力。您必須使用第三方庫。由于您明確表示您不想使用 tkinterhtml ,因此您必須找到其他一些第三方渲染器。
uj5u.com熱心網友回復:
我已經通過使用tkinterweb庫解決了這個問題。
代碼:
import tkinter
from tkinterweb import HtmlFrame
screen = tkinter.Tk()
screen.geometry("700x700")
frame = HtmlFrame(screen, horizontal_scrollbar="auto")
urlInput = tkinter.Entry(screen)
def search():
frame.load_website(urlInput.get())
button = tkinter.Button(screen,text="search",command=search)
frame = HtmlFrame(screen)
urlInput.grid(row=0,column=0,columnspan=2)
button.grid(row=1,column=0)
frame.grid(row=2,column=0)
screen.mainloop()
這適用于任何想知道我如何解決它的人
uj5u.com熱心網友回復:
您將google.com頁面解碼為'utf8'or 'utf16'; 但是,該google.com頁面使用 ISO-8859-1 編碼:
回傳的標頭google.com是:
Content-Type: text/html; charset=ISO-8859-1
您需要使用解碼頁面'ISO-8859-1'以避免“編解碼器無法解碼位元組 0x..”錯誤。
uj5u.com熱心網友回復:
Flask 有一個稱為渲染模板的工具,我將它用于我的網站,而且實作起來也不難......這里有一個例子:
from flask import Flask
from flask import render_template
app = Flask(__name__)
#sets app route and renders file
@app.route('/')
def index():
return render_template('index.html')
if __name__ == "__main__":
app.run(host='0.0.0.0', port="any port number here", debug=True)
#debug just refreshes the main file (app.py or something.py) when a change is made
我建議您也查看 Flask 上的檔案以全面了解它,我真的希望這能回答您的問題 https://flask.palletsprojects.com/en/2.0.x/
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/446182.html
上一篇:HTML和CSS影像填充不起作用
