Python 网络抓取:睡眠和请求之间的区别(页面,超时=x)

Python web scraping: difference between sleep and request(page, timeout=x)

当循环抓取多个网站时,我注意到它们之间的速度差异很大,

sleep(10)
response = requests.get(url)

并且,

response = requests.get(url, timeout=10)

也就是说,timeout要快得多。

此外,对于这两种设置,我预计在请求下一页之前每页的抓取持续时间至少为 10 秒,但事实并非如此。

  1. 为什么速度会有这么大的差异?
  2. 为什么每页抓取时长不到10秒?

我现在使用多处理,但我想记住上述内容也适用于非多处理。

time.sleep 将您的脚本从 运行ning 停止一定秒数,而 timeout 是等待检索 url 的最长时间。如果在 timeout 时间结束之前检索数据,将跳过剩余时间。所以使用 timeout.

可以花费不到 10 秒的时间

time.sleep 不同,它会完全暂停您的脚本,直到它完成休眠,然后它会 运行 您的请求再花几秒钟。所以 time.sleep 每次都需要 10 多秒。

它们的用途非常不同,但对于您的情况,您应该制作一个计时器,这样如果它在 10 秒之前完成,就让程序等待。

response = requests.get(url, timeout=10)
# timeout specifies the maximum time program will wait for request to complete before throwing exception. It is not necessary that program will pause for 10 seconds. If response is returned early the program won't wait anymore.

详细了解 requests 超时 here

time.sleep 导致您的主线程休眠,因此您的程序将始终等待 10 秒,然后再向 url.

发出请求