如何在html div中显示Python print()

时间:2018-10-03 18:18:21

标签: python ajax django

我正在使用Django编写我的网站。在编写Python代码期间,我有许多打印功能。它们全部显示在标准控制台中。我想不仅在控制台中,而且在HTML代码中以div显示(实时显示而不刷新页面)所有div中的打印内容。怎么做? 我的代码可以: 您按下按钮,然后selenium开始使用ajax而不刷新页面,在此期间,我想使用div在页面上显示进度。

例如,我的代码:

views.py
bot = Instagram()

class InstabotFormView(AjaxFormMixin, FormView):
    form_class = LoginInstagramForm
    template_name = 'instabot.html'
    success_url = 'runinstabot.html'

    def form_invalid(self, form):
        response = super(InstabotFormView, self).form_invalid(form)
        if self.request.is_ajax():
            return JsonResponse(form.errors, status=400)
        else:
            return response

    def form_valid(self, form):
        response = super(InstabotFormView, self).form_valid(form)
        login = form.cleaned_data.get('login')
        password = form.cleaned_data.get('password')
        tagi = form.cleaned_data.get('tags')
        func = form.cleaned_data.get('function')
        tags = []
        tagi = tagi.split(',')
        tags.extend(tagi)
        if self.request.is_ajax():
            print('It is AJAX')
            bot.login(login,password)
            bot.search(tags)
            if func == '1':
                bot.downloadPhoto(tags)
            elif func == '2':
                bot.doCalculation(tags)
            print(tags)
            data = {
                'message': "Succesfully  opened Selenium."
            }
            return JsonResponse(data)
        else:
            return response

Instagram()
    def downloadPhoto(self):
        i = 0
        time.sleep(2)
        self.driver.find_element_by_xpath('/html/body/span/section/main/div/header/section/ul/li[2]/a').click()
        print('Start function downloadPhoto')
        print(self.myCurrentList)

        for photo in self.myCurrentList:
            followerPhoto = self.myCurrentList.index(photo) + 1
            print(followerPhoto)

如何在html div中显示def downloadPhoto(self)的所有打印内容?

2 个答案:

答案 0 :(得分:3)

永远不要在django应用中使用打印件。如果要打印有用的信息,则必须使用python和django中的well文档提供的日志记录工具:https://docs.djangoproject.com/en/2.1/topics/logging/

要向您的客户端实时发送通知,您必须在客户端和服务器之间实现一个full duplex通道。允许您执行此操作的技术是websocket,您可以使用django-channels包在项目中实现websocket。请记住,必须对基础架构进行一些更改。

答案 1 :(得分:1)

这是对某些更改的粗略尝试,尽管我不确定这正是您要的内容。最终,您需要将用Selenium抓取的HTML内容放入视图的data字典中,以便它成为JsonResponse将呈现的内容的一部分。

关于Instagram类,我不清楚您为什么要打印出self.myCurrentList,所以现在暂时跳过。

Instagram()
    def downloadPhoto(self):
        i = 0
        time.sleep(2)
        self.driver.find_element_by_xpath('/html/body/span/section/main/div/header/section/ul/li[2]/a').click()
        # don't do this: 
        # print('Start function downloadPhoto')
        # not sure if this is needed or not, skipping it for now:
        # print(self.myCurrentList)

        photos = []
        for photo in self.myCurrentList:
            photos.append(self.myCurrentList.index(photo) + 1)

        return photos

# views.py
bot = Instagram()
class InstabotFormView(AjaxFormMixin, FormView):
    ...
    def form_valid(self, form):
        ...
        if self.request.is_ajax():
            # set a variable to hold the output from Instagram.downloadPhoto
            photos = None 
            # get rid of this:
            # print('It is AJAX')
            bot.login(login,password)
            bot.search(tags)
            if func == '1':
                # capture the output from Instagram.downloadPhoto
                photos = bot.downloadPhoto(tags)
            elif func == '2':
                bot.doCalculation(tags)

            # can't do this, needs to be moved into the data for your JsonResponse:
            # print(tags)
            data = {
                'message': "Succesfully  opened Selenium.",
                # we don't know what kind of data this is, needs to be a dict/list though, so 
                # JsonResponse knows how to render it for the response
                'tags': tags 
            }

            if photos:
                data['photos'] = photos

            return JsonResponse(data)
        else:
            return response

在我看来,这是一个总体思路:您当前要打印的内容需要转移到data字典中,然后再传递给JsonResponse。这应该导致以下响应:

{
  "message": "Successfully opened Selenium.",
  "tags": [
    "no idea",
    "what kind",
    "of data",
    "this is"
  ],
  "photos": [
    "<div>Some sort of HTML content that Selenium scraped?</div>",
    "<div>Some sort of HTML content that Selenium scraped?</div>",
    "<div>Some sort of HTML content that Selenium scraped?</div>",
  ]
}

再次-不确定这是否完全是您想要的东西,我只是想说明一种从print语句中获取该内容的方法,并且进入您的JsonResponse。很高兴为您提供进一步的帮助,请让我知道是否有其他问题。