import requests
python中有一個(gè)第三方庫(kù)‘requests’中提供了所有和http請(qǐng)求相關(guān)的函數(shù)
1.get請(qǐng)求
get(url, params=None) - 發(fā)送請(qǐng)求獲取服務(wù)器返回的響應(yīng)
url - 請(qǐng)求地址
params - 請(qǐng)求參數(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.獲取請(qǐng)求結(jié)果
1)響應(yīng)頭
{'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)響應(yīng)體(數(shù)據(jù))
a.獲取二進(jìn)制對(duì)應(yīng)的原數(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轉(zhuǎn)換成python對(duì)應(yīng)的數(shù)據(jù))
json = response.json()
print(type(json))
多線程基礎(chǔ)
import threading
from time import sleep
from datetime import datetime
1.線程
每個(gè)進(jìn)程中默認(rèn)都有一個(gè)線程,這個(gè)線程叫主線程。其它線程叫子線程
threading模塊中Thread的對(duì)象就是線程對(duì)象,當(dāng)程序中需要子線程就創(chuàng)建Thread類的對(duì)象
def download(film_name):
print('開(kāi)始下載%s:%s' % (film_name, datetime.now()))
print(threading.current_thread())
sleep(5)
print('%s下載結(jié)束:%s' % (film_name, datetime.now()))
if __name__ == '__main__':
download('ss')
download('aa')
download('bb')
# 1.創(chuàng)建線程對(duì)象
"""
Thread(target=None, args=()) - 創(chuàng)建并返回一個(gè)子線程對(duì)象
target - 函數(shù)類型(function),這個(gè)函數(shù)在線程啟動(dòng)的時(shí)候會(huì)在子線程中執(zhí)行
args - 元祖(tuple),給target中的函數(shù)傳參的實(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.啟動(dòng)線程
"""
線程對(duì)象.start() - 讓線程取執(zhí)行線程中的任務(wù)
"""
t1.start()
t2.start()
t3.start()
from threading import *
from time import sleep
from datetime import datetime
程序結(jié)束
線程中的任務(wù)執(zhí)行完成線程就結(jié)束;程序出現(xiàn)異常結(jié)束的是異常的線程,不是進(jìn)程(其它線程還會(huì)進(jìn)行)
進(jìn)程中的所有線程結(jié)束進(jìn)程才結(jié)束
1.聲明一個(gè)類繼承Thread
2.實(shí)現(xiàn)類中的run方法,這個(gè)方法中的代碼就是需要在子線程中執(zhí)行的代碼
3.需要子線程的時(shí)候就創(chuàng)建自己聲明類的線程對(duì)象,不需要傳參
class DownloadThread(Thread):
def __init__(self, film_name):
super().__init__()
self.film_name = film_name
def run(self) -> None:
print(current_thread())
print('開(kāi)始下載%s:%s' % (self.film_name, datetime.now()))
# print(current_thread())
sleep(5)
print('%s下載結(jié)束:%s' % (self.film_name, datetime.now()))
if __name__ == '__main__':
t1 = DownloadThread('jsxc')
t2 = DownloadThread('kjfd')
t1.start()
t2.start()