Python - 获取 URL、解析和打印 PDF

标签 python django beautifulsoup reportlab

我正在尝试获取 URL 的 HTML 源代码,对其进行解析,然后将结果打印为 PDF。

为此,我想依赖 BeautifulSoup、urllib2 和 reportlab,但我不知道如何正确组合它们。

运行 django 1.3.1 开发服务器并访问 View 时,出现错误'module' object is not callable

这是我的代码:

from reportlab.pdfgen import canvas
from cStringIO import StringIO
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template import RequestContext
# Fetching the URL
import urllib2

# Parsing the HTML
from BeautifulSoup import BeautifulSoup

# The ConverterForm
from django import forms

class ConverterForm(forms.Form):
    # Use textarea instead the default TextInput.
    html_files = forms.CharField(widget=forms.Textarea)
    filename = forms.CharField()

# Create your views here.
def create_pdf(request):
    # If the form has been submitted
    if request.method == 'POST':
        # A form bound to the POST data
        form = ConverterForm(request.POST)
    # All validation rules pass
    if form.is_valid():
        # PDF creation process
        # Assign variables
        html_files = form.cleaned_data['html_files']
        filename = form.cleaned_data['filename']

        # Create the HttpResponse object with the appropriate PDF headers.
        response = HttpResponse(mimetype='application/pdf')
        # The use of attachment forces the Save as dialog to open.
        response['Content-Disposition'] = 'attachment; filename=%s.pdf' % filename

        buffer = StringIO()

        # Get the page source
        page = urllib2.urlopen(html_files)
        html = page.read()

        # Parse the page source
        soup = BeautifulSoup(html)

        # Create the PDF object, using the StringIO() object as its "file".
        p = canvas.Canvas(buffer)

        # Draw things on the PDF and generate the PDF.
        # See ReportLab documentation for full list of functions.
        p.drawString(100, 100, soup)

        # Close the PDF object cleanly.
        p.showPage()
        p.save()

        # Get the value of the StringIO buffer and write it to the response.
        pdf = buffer.getvalue()
        buffer.close()
        response.write(pdf)
        return response

    else:
        # An unbound form
        form = ConverterForm()

    # For RequestContext in relation to csrf see more here:
    # https://docs.djangoproject.com/en/1.3/intro/tutorial04/
    return render_to_response('converter/index.html', {
    'form': form,
    }, context_instance=RequestContext(request))

最佳答案

您需要导入BeautifulSoup类:

from BeautifulSoup import BeautifulSoup

这可能会令人困惑,因为模块和类具有相同的基名称。

关于Python - 获取 URL、解析和打印 PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9851982/

相关文章:

python - 带有自定义用户模型注册的 django-registration-redux NotImplementedError

python - 在 Mac Os X Mavericks (10.9) 上安装 Pillow for Python 3.4

python - 如何让pycharm解析当前项目文件夹中的引用编译模块

javascript - Django:如果url是用户手动编写的,则重定向

django - Whitenoise.storage.MissingFileError : The JS file 'drf-yasg\redoc\redoc.min.js' references a file which could not be found

python - 与 BeautifulSoup 一起逃离……

python - 使用 BeautifulSoup 从 span 类中提取 anchor 文本

python-3.x - 如何使用Beautifulsoup4检查父标签是否有名称不是 "div"的直接子标签

python - Python错误 “TypeError: unorderable types: list() <= int()”

python - 基于索引的numpy reshape