Python请求(>=1.*):如何禁用keep alive?

2024-05-14 17:20:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用请求模块编程一个简单的网络爬虫程序,我想知道如何禁用它的-默认-保持活动的feauture。

我试着用:

s = requests.session()
s.config['keep_alive'] = False

但是,我得到了一个错误,说明session对象没有属性'config',我认为它是用新版本更改的,但是我似乎在官方文档中找不到如何执行它。

事实上,当我在一个特定的网站上运行爬虫程序时,它最多只能得到5个页面,然后无限循环,所以我认为它与“保持活力”功能有关!

PS:请求是一个很好的网络爬虫模块吗?有更适合的吗?

谢谢你!


Tags: 模块对象程序网络configfalse属性session
3条回答

这行得通

s = requests.session()
s.keep_alive = False

Answered in the comments of a similar question.

我不确定,但是在使用请求发送GET请求时,可以尝试将{“Connection”:“close”}作为HTTP头传递吗。这将在服务器返回响应时立即关闭连接。

>>> headers = {"Connection": "close"}
>>> r = requests.get('https://example.xcom', headers=headers)

正如@praveen建议的那样,我们应该使用HTTP/1.1Connection: close通知服务器在响应完成后应该关闭连接。

以下是RFC 2616中对它的描述:

HTTP/1.1 defines the "close" connection option for the sender to signal that the connection will be closed after completion of the response. For example,

Connection: close

in either the request or the response header fields indicates that the connection SHOULD NOT be considered `persistent' (section 8.1) after the current request/response is complete.

HTTP/1.1 applications that do not support persistent connections MUST include the "close" connection option in every message.

相关问题 更多 >

    热门问题