python request text 和 content的區別;requests.get().json()作用;string.rfind()作用

1 test和content簡介
resp.text返回的是Unicode型的數據。

resp.content返回的是bytes型也就是二進制的數據。

如果你想取文本,可以通過r.text。
如果想取圖片,文件,則可以通過r.content。

# requests庫的使用:通過requests實現一個訪問數據接口從中下載圖片保存到本地



from time import time
from threading import Thread
import requests


class DownloadHandler(Thread):

    def __init__(self, url):
        super().__init__()
        self._url = url

    def run(self):
        # string.rfind(substr) 返回字符串中substr最後出現的一次位置
        filename = self._url[self._url.rfind('/') + 1:]
        print('Start downloading: %s' % filename)
        resp = requests.get(self._url)
        with open(filename, 'wb') as f:
            # 返回bytes型二進制數據(獲取圖片文件用resp.content)
            f.write(resp.content)


def main():
    start_time = time()
    # requests.get()構造一個想服務器請求資源的url對象
    # 返回值是一個包含服務器資源的Response對象
    resp = requests.get('http://api.tianapi.com/meinv/index?key=024759fe3b09b55caf5d462e8002d716&num=10')
    # print(resp)
    # print(type(resp)) # 返回Response對象
    # Requests中內置一個JSON解碼器,可處理JSON數據返回成字典
    data_model = resp.json()
    # print(data_model)
    # print(type(data_model)) #返回 dict類型
    download_threads = []
    for mn_dict in data_model['newslist']:
        url = mn_dict['picUrl']
        # DownloadHandler(url).start()
        dt = DownloadHandler(url)
        download_threads.append(dt)
        dt.start()
    # 等待所有線程執行結束
    for dt in download_threads:
        dt.join()
    # 花費時間
    end_time = time()
    print("Total Cost %s" % (end_time - start_time))

if __name__ ==  '__main__':
    main()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章