【问题标题】:Problems running beautifulsoup4 within Apache/mod_python/Django在 Apache/mod_python/Django 中运行 beautifulsoup4 的问题
【发布时间】:2012-09-19 01:45:00
【问题描述】:

我正在尝试在 Django 中使用 BeautifulSoup 版本 4 动态呈现 HTML 页面(使用 Apache2 和 mod_python)。 但是,只要我将任何 HTML 字符串传递给 BeautifulSoup 构造函数(参见下面的代码),浏览器就会挂起等待网络服务器。我在 CLI 中尝试了等效代码,它就像一个魅力。所以我猜这与 BeautifulSoups 环境有关,在这种情况下是 Django + Apache + mod_python。

import bs4
import django.shortcuts as shortcuts

def test(request):
    s = bs4.BeautifulSoup('<b>asdf</b>')
    return shortcuts.render_to_response('test.html', {})

我已经使用 pip pip install beautifulsoup4 安装了 BeautifulSoup。我尝试使用标准 Debian 软件包 apt-get install python-beautifulsoup 安装 BeautifulSoup3,然后以下等效代码可以正常工作(来自浏览器和 CLI)。

from BeautifulSoup import BeautifulSoup
import django.shortcuts as shortcuts

def test(request):
    s = BeautifulSoup('<b>asdf</b>')
    return shortcuts.render_to_response('test.html', {})

我查看了 Apache 的访问和错误日​​志,但它们没有显示任何信息显示停止的请求发生了什么。我还检查了 /var/log/syslog 和 /var/log/messages,但没有更多信息。

这是我使用的 Apache 配置:

<VirtualHost *:80>
    DocumentRoot /home/nandersson/src
    <Directory /home/nandersson/src>
        SetHandler python-program
        PythonHandler django.core.handlers.modpython
        SetEnv DJANGO_SETTINGS_MODULE app.settings
        PythonOption django.root /home/nandersson/src
        PythonDebug On
        PythonPath "['/home/nandersson/src'] + sys.path"
    </Directory>

    <Location "/media/">
        SetHandler None
    </Location>
    <Location "/app/poc/">
        SetHandler None
    </Location>
</VirtualHost>

我不确定如何进一步调试,不确定它是否是错误。 有没有人知道如何解决这个问题或遇到过类似的问题?

【问题讨论】:

  • 向我们展示您使用的 apache 配置。以及 wsgi.py 文件的内容。
  • 我更新了这个,谢谢。但是我使用的是前面提到的 mod_python,所以没有 wsgi.py 可以显示。
  • 完全不相关,但你应该像这样导入你的包:from django import shorcuts,因为你使用的是 python2.7

标签: python django apache beautifulsoup mod-python


【解决方案1】:

我正在使用 Apache2 和 mod_python。我通过显式传递“html.parser”来解决挂起问题。

s = bs4.BeautifulSoup('<b>asdf</b>', 'html.parser')

【讨论】:

  • 这行得通!谢谢。但是我更喜欢使用'lxml'来提高性能,但是会发生同样的错误。你知道为什么会这样吗?这是一个错误吗?
  • 抱歉回复晚了。为了获得更好的性能,我已更改为使用 lxml。我完全没有遇到任何问题。你的代码是什么?
  • 啊,我意识到 mod_python 已经过时了。 mod_wsgi 是正在推送的模块更新。当我替换 mod_python 并使用 lxml 时,这个问题就消失了。
【解决方案2】:

这可能是 here 描述的 Cython 和 mod_wsgi 之间的交互,并在 Beautiful Soup 上下文 here 中进行了探索。这里是earlierquestions,和你的类似。

【讨论】:

  • 如描述中所说,我使用的不是 mod_wsgi 而是 mod_python。
【解决方案3】:

试试

doc = BeautifulSoup(html, 'html5lib')

在我的情况下,'html.parser' 经常导致 HTMLParseError https://groups.google.com/forum/?fromgroups=#!topic/beautifulsoup/x_L9FpDdqkc

【讨论】:

    【解决方案4】:

    大约一年前我遇到过同样的问题,刚刚尝试使用新版本的 BeautifulSoup 4.3.2 进行类似的设置 (django+mod_wsgi+apache2),似乎问题已得到解决。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-06
      • 2010-11-07
      • 2012-08-17
      • 2012-10-02
      • 1970-01-01
      相关资源
      最近更新 更多