打印相同的 HTTPResponse 对象 returns 不同的输出 - Python

Printing same HTTPResponse Object returns different outputs - Python

def crawl(url):
    html = getHTML(url) # getHTML() retruns HTTPResponse
    print(html.read()) # PRINT STATMENT 1
    if (html == None):
        print("Error getting HTML")
    else:
        # parse html
        bsObj = BeautifulSoup(html, "lxml")
        # print data
        try:
            print(bsObj.h1.get_text())
        except AttributeError as e:
            print(e)

        print(html.read()) # PRINT STAETMENT 2

我不明白的是..

PRINT STATEMENT 1 打印整个 html 而 PRINT STATEMENT 2 仅打印 b''

这里发生了什么? ..我对 Python 很陌生。

html 是一个 HTTPResponse 对象。 HTTPResponse 支持类文件操作,例如read()

就像读取文件一样,read() 消耗可用数据并将文件指针移动到 file/data 的 end。随后的 read() 与 return.

无关

您有两个选择:

  1. 使用seek()方法读取后将文件指针重置为开头:

    print(html.read())
    html.seek(0) # moves the file pointer to byte 0 relative to the start of the file/data
    
  2. 改为保存结果:

    html_body = html.read()
    print(html_body)
    

通常,您会使用第二个选项,因为它更容易重复使用 html_body