首页 > 解决方案 > Python - 在异步函数中使用 response.content?

问题描述

所以。

我创建了一个异步类库,以抓取大量 url,创建我的类我使用了一些其他代码,他们使用了 response.text() 并且工作正常。今天抓取一个不同的网站,我注意到缺少一些 html 内容,所以我尝试以正常方式执行请求,并注意到我通常使用 responste.content 而在我的异步库之外使用请求库。

这是定义:

    async def fetch(self, session, url):
        try:
            async with session.get(url) as response:
                
                # 1. Extracting the Text:
                text = await response.text()
                conection_status = response.status
                # 2. Extracting the infos from the url:
                dict_content = await self.extract_dict_content(text, url,conection_status )
                
                return text, url, dict_content,conection_status
        except Exception as e:
            print('!!!!!! WARNING !!!!')
            print(str(e))
            
            
    async def extract_dict_content(self, text, url,conection_status):
        try:
            
            scraped = BeautifulSoup(text, 'html.parser')
            return self.scrap_def(scraped, url, conection_status)
  
        except Exception as e:
            print(str(e))

所以我尝试为 .content 更改 .text() 但我收到此错误: 'StreamReader' object is not callable

我读到有些网站喜欢嵌套代码,使用 .text() 时可能不会出现一些文本,所以我必须使用 .content 来获取完整的 HTML 代码。

有人可以帮我找到解决方案吗?

标签: pythonasynchronousasync-awaitpython-requestsstreamreader

解决方案


推荐阅读