【问题标题】:mutiline python script in html (pyscript)html中的多行python脚本(pyscript)
【发布时间】:2022-10-31 03:18:57
【问题描述】:

我尝试在 html 中使用 pyscript,但我只能让它在一行代码中工作,有人可以帮我让它在下面的代码中工作吗?

def vpn(website):
 from selenium import webdriver
 from selenium.webdriver.chrome.options import Options
    
 chrome_options = Options()
 chrome_options.add_argument('--no-sandbox')
 chrome_options.add_argument('--disable-dev-shm-usage')
    
 driver = webdriver.Chrome(options=chrome_options)
 driver.get(website)
    
vpn("chrome://newtab/")

我什至认为可行的唯一代码是:

<!DOCTYPE html>
<html>
 <pyscript>
  def vpn(website):
   from selenium import webdriver
   from selenium.webdriver.chrome.options import Options
    
   chrome_options = Options()
   chrome_options.add_argument('--no-sandbox')
   chrome_options.add_argument('--disable-dev-shm-usage')
   
   driver = webdriver.Chrome(options=chrome_options)
   driver.get(website)
    
  vpn("chrome://newtab/")
 </pyscript>
</html>

当我运行上述代码时,我收到以下错误消息:

def vpn(website): from selenium import webdriver from selenium.webdriver.chrome.options import Options chrome_options = Options() chrome_options.add_argument('--no-sandbox') chrome_options.add_argument('--disable-dev-shm-usage') driver = webdriver.Chrome(options=chrome_options) driver.get(website) vpn("chrome://newtab/")

有谁知道其他方法可以做到这一点?

【问题讨论】:

标签: python html selenium selenium-webdriver pyscript


【解决方案1】:

也许,只是也许,有一个缩进问题。如果制表符仅用于缩进一次,则在 html 文件中编写的 Pyscript 代码将出错。很难注意到它,因为使用和不使用选项卡的代码看起来是一样的。例子:

<py-script>
import pandas as pd
data = {'A': [1, 2, 3, 4, 5], 'B': ['A', 'B', 'C', 'D', 'E']}
if data:
____df = pd.DataFrame(data)
____print('Print from index.html')
____print(df)
____pyscript.write('out', df)
</py-script>

上面的代码可以正常工作,因为有 4 个空格( _ _ _ _ )用于缩进。下面的代码...

<py-script>
import pandas as pd
data = {'A': [1, 2, 3, 4, 5], 'B': ['A', 'B', 'C', 'D', 'E']}
if data:
____df = pd.DataFrame(data)
--->print('Print from index.html')
____print(df)
____pyscript.write('out', df)
</py-script>

...将导致错误,因为该命令print('从 index.html 打印')使用制表符 (--->) 缩进。在我的情况下,制表符缩进设置为 4 个字符,但只是使用制表符字符而不是 4 个空格这一事实会导致错误。
我根本不在 html 文件中编写 pyscript 代码。相反,我在文件中执行此操作并将其作为 pyscript 标签的 src 属性放入 html 中。
在这种情况下,相同的代码是:
main.py 文件:

import pandas as pd
data = {'A': [1, 2, 3, 4, 5], 'B': ['A', 'B', 'C', 'D', 'E']}
if data:
    df = pd.DataFrame(data)
    print('Print from main.py')
    print(df)
    pyscript.write('out', df)

index.html 文件

...
<py-script id="outerPyMain" src="./main.py"></py-script>
...

此外,在 py-env 标记中也实现了相同的“无制表符字符”规则。
不知道这是不是你的情况,但无论如何......
问候...

【讨论】:

    猜你喜欢
    • 2022-06-16
    • 2016-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-10
    • 2021-04-11
    • 2017-04-12
    相关资源
    最近更新 更多