一、Python的sleep
Python的sleep是一種以秒為單位的休眠函數,可以暫停程序的執行一段時間。該方法從time
模塊中引入,語法如下:
import time
time.sleep(seconds)
二、pythonsleep1秒
pythonsleep1秒是一種休眠1秒的方法,即在程序執行時暫停1秒,可以用於控制程序的執行速度。其實際調用sleep方法,語法如下:
import time
time.sleep(1)
三、Python中sleep的單位
Python的sleep方法參數是秒,但是在實際編程中,我們有時候需要用毫秒作為單位的延時,可以通過將秒轉換為毫秒的方式實現。
import time
time.sleep(0.001) # 延時1毫秒
四、pythonsleep語句
pythonsleep語句也是一種休眠語句,與pythonsleep方法類似,可以用於暫停程序的執行一段時間。其語法如下:
from time import sleep
sleep(seconds)
五、pythonsleep函數
pythonsleep函數也是一種休眠函數,與sleep方法類似,也可以用於暫停程序的執行一段時間。其語法如下:
from time import sleep
def pause(seconds):
sleep(seconds)
六、Python zeros方法
Python zeros方法可以用於創建一個指定長度的全零數組。它的參數可以是元組、列表、整數等,返回的結果是一個全零數組。其語法如下:
import numpy as np
zeros_array = np.zeros((3, 4)) # 3行4列,元素值為0
七、實際應用案例
pythonsleep在實際開發中的應用十分廣泛,比如:
- 控制程序執行速度,調試代碼
- 模擬用戶操作,延時響應
- 動態展示進度條
- 爬蟲中請求限速
實例1:模擬用戶操作,延時響應
from selenium import webdriver
import time
driver = webdriver.Chrome()
driver.get('https://www.baidu.com')
time.sleep(2) # 等待頁面加載完成
search_input = driver.find_element_by_xpath('//*[@id="kw"]')
search_input.send_keys('python')
search_input.submit()
time.sleep(3) # 等待搜索結果展示
driver.quit()
實例2:動態展示進度條
import time
import sys
bar_length = 50
for i in range(100):
time.sleep(0.1)
percent = int((i / 100) * bar_length)
bar = '#' * percent + '-' * (bar_length - percent)
sys.stdout.write('\r' + bar + ' [%d%%]' % (i))
sys.stdout.flush()
實例3:爬蟲中請求限速
import requests
import time
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36'
}
url = 'https://www.baidu.com'
for i in range(3):
response = requests.get(url, headers=headers)
time.sleep(2) # 請求限速
print(response.status_code)
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/200649.html