import requests
python中有一個第三方庫‘requests’中提供了所有和http請求相關的函數(shù)
1.get請求
get(url, params=None) - 發(fā)送請求獲取服務器返回的響應
url - 請求地址
params - 請求參數(shù),字典
方法1:適用于get和post,只需要將requests.后面改為post (接口是post或get的前提下)
url = 'http://ww.apiopen.top/satinApi'
params = {'type': 1, 'page': 2}
response = requests.get(url, params)
print(response)
方法2:只適用于get
url = 'http://ww.apiopen.top/satinApi?type=1&page=1'
response = requests.get(url)
print(response)
2.獲取請求結果
1)響應頭
{'Server': 'nginx', 'Date': 'Thu, 15 Aug 2019 03:41:29 GMT', 'Content-Type': 'text/html', 'Content-Length': '162', 'Connection': 'keep-alive'}
print(response.headers)
2)響應體(數(shù)據(jù))
a.獲取二進制對應的原數(shù)據(jù)(數(shù)據(jù)本身是圖片阿趁、壓縮文件慈迈、視頻等文件數(shù)據(jù))
content = response.content
print(type(content))
b.獲取字符類型的數(shù)據(jù)
text = response.text
print(type(text))
c.獲取json數(shù)據(jù)(json轉換成python對應的數(shù)據(jù))
json = response.json()
print(type(json))
多線程基礎
import threading
from time import sleep
from datetime import datetime
1.線程
每個進程中默認都有一個線程媳否,這個線程叫主線程。其它線程叫子線程
threading模塊中Thread的對象就是線程對象,當程序中需要子線程就創(chuàng)建Thread類的對象
def download(film_name):
print('開始下載%s:%s' % (film_name, datetime.now()))
print(threading.current_thread())
sleep(5)
print('%s下載結束:%s' % (film_name, datetime.now()))
if __name__ == '__main__':
download('ss')
download('aa')
download('bb')
# 1.創(chuàng)建線程對象
"""
Thread(target=None, args=()) - 創(chuàng)建并返回一個子線程對象
target - 函數(shù)類型(function),這個函數(shù)在線程啟動的時候會在子線程中執(zhí)行
args - 元祖(tuple)慎框,給target中的函數(shù)傳參的實參
"""
t1 = threading.Thread(target=download, args=('cxx',))
t2 = threading.Thread(target=download, args=('cxk',))
t3 = threading.Thread(target=download, args=('das',))
print(threading.current_thread())
# 2.啟動線程
"""
線程對象.start() - 讓線程取執(zhí)行線程中的任務
"""
t1.start()
t2.start()
t3.start()
from threading import *
from time import sleep
from datetime import datetime
程序結束
線程中的任務執(zhí)行完成線程就結束;程序出現(xiàn)異常結束的是異常的線程后添,不是進程(其它線程還會進行)
進程中的所有線程結束進程才結束
1.聲明一個類繼承Thread
2.實現(xiàn)類中的run方法笨枯,這個方法中的代碼就是需要在子線程中執(zhí)行的代碼
3.需要子線程的時候就創(chuàng)建自己聲明類的線程對象,不需要傳參
class DownloadThread(Thread):
def __init__(self, film_name):
super().__init__()
self.film_name = film_name
def run(self) -> None:
print(current_thread())
print('開始下載%s:%s' % (self.film_name, datetime.now()))
# print(current_thread())
sleep(5)
print('%s下載結束:%s' % (self.film_name, datetime.now()))
if __name__ == '__main__':
t1 = DownloadThread('jsxc')
t2 = DownloadThread('kjfd')
t1.start()
t2.start()