请求:.text 格式的说明

Requests: Explanation of the .text format

我正在使用 requests 模块和 Python 2.7 构建一个基本的网络爬虫。

source_code = requests.get(url)
plain_text = source_code.text

现在,在上面的代码行中,我将指定 URL 的源代码和其他元数据存储在 source_code 变量中。现在,在 source_code.text 中,.text 属性到底是什么?它不是一个函数。我在文档中也找不到任何解释 .text 的起源或特征的内容。

requests.get()returns一个Response object;正是该对象具有 .text 属性;它 不是 'source code' 而是 URL,它是一个对象,可以让您访问响应的源代码(正文),以及其他信息。 Response.text 属性为您提供响应正文,解码为 unicode.

请参阅快速入门文档的 Response Content section

When you make a request, Requests makes educated guesses about the encoding of the response based on the HTTP headers. The text encoding guessed by Requests is used when you access r.text.

可以在 API 文档中找到更多信息,请参阅 Response.text entry:

Content of the response, in unicode.

If Response.encoding is None, encoding will be guessed using chardet.

The encoding of the response content is determined based solely on HTTP headers, following RFC 2616 to the letter. If you can take advantage of non-HTTP knowledge to make a better guess at the encoding, you should set r.encoding appropriately before accessing this property.

您还可以使用 Response.content 访问未解码的响应正文,作为原始字节。

这一行

 source_code = requests.get(url)

source_code 有一个 response 对象,不是源代码。

应该是

response = requests.get(url)
source_code = response.text