首页 > 解决方案 > 如何从Django中的网页获取html

问题描述

我试图在 Django 中实现一些测试,我需要用字符串检查网页上的数据,但我无法从网页中检索数据。那么,如何从网页获取数据(html)?

我的测试.py

from rest_framework.test import APITestCase

class TicketTestCase(APITestCase):

    def test_user_details_on_ticket_id(self):

        response = self.client.get(f"/api/ticket/1")
        print(response.content) # this returns empty data in bytes

        # I want to check this
        #self.assertEquals(response.data, "helloworld")

标签: pythondjangodjango-testingdjango-tests

解决方案


你在做什么是正确的。您可以使用response.content. 问题是您在网址末尾缺少斜杠,因此网址应该是

 response = self.client.get(f"/api/ticket/1/")

代替

 response = self.client.get(f"/api/ticket/1")

推荐阅读