【问题标题】:I want to pass the array to the template of bottle and display its contents我想将数组传递给瓶子的模板并显示其内容
【发布时间】:2017-10-13 16:21:47
【问题描述】:

环境

・Python 3.6.0

・瓶子 0.13-dev

・mod_wsgi-4.5.15


在网络上尝试以下代码会导致 500 错误

500 内部服务器错误


应用程序/wsgi

# -*- coding:utf-8 -*-
import sys, os
dirpath = os.path.dirname(os.path.abspath(__file__))
sys.path.append(dirpath)
sys.path.append('../')
os.chdir(dirpath)
import bottle
import index
application = bottle.default_app()

index.py

from urllib.request import urlopen
from bs4 import BeautifulSoup
from bottle import route, view

@route('/')
@view("index_template")
def index():
    html = urlopen("https://en.wikipedia.org/wiki/Kevin_Bacon")
    internalLinks=[]
    bsObj = BeautifulSoup(html, "html.parser")
        for link in bsObj.findAll("a"):
            if 'href' in links.attr:
                internalLinks.append(links.attr['href'])
    return dict(internalLinks=internalLinks)

views/index_template.tpl

{{internalLinks}}

apache 日志

[error]  mod_wsgi (pid=23613): Target WSGI script '/app.wsgi' cannot be loaded as Python module.
[error]  mod_wsgi (pid=23613): Exception occurred processing WSGI script '/app.wsgi'.
[error]  Traceback (most recent call last):
[error]    File "/app.wsgi", line 8, in <module>
[error]      import index
[error]    File "/index.py", line 11
[error]      for link in bsObj.findAll("a"):
[error]      ^
[error]  IndentationError: unexpected indent

【问题讨论】:

    标签: python python-3.x beautifulsoup bottle


    【解决方案1】:

    日志报告IndentationError,因此代码中的缩进有问题:具体而言,for 循环过度缩进,for 语句应与bsObj 赋值处于同一级别.

    您还需要使变量名称保持一致 (link|links) 并使用 attrs 属性,而不是 attr。修复了以下代码(未经测试)。

    @route('/')
    @view("index_template")
    def index():
        html = urlopen("https://en.wikipedia.org/wiki/Kevin_Bacon")
        internalLinks=[]
        bsObj = BeautifulSoup(html, "html.parser")
        for link in bsObj.findAll("a"):
            if 'href' in link.attrs:
                internalLinks.append(link.attrs['href'])
        return dict(internalLinks=internalLinks)
    

    【讨论】:

      猜你喜欢
      • 2021-09-12
      • 1970-01-01
      • 1970-01-01
      • 2013-02-14
      • 1970-01-01
      • 1970-01-01
      • 2016-06-03
      • 2021-10-29
      • 1970-01-01
      相关资源
      最近更新 更多