1. 程式人生 > 程式設計 >Python基於httpx模組實現傳送請求

Python基於httpx模組實現傳送請求

一、httpx模組是什麼?

一個用於http請求的模組,類似於requests、aiohttp;
既能傳送同步請求(是指在單程序單執行緒的程式碼中,發起一次請求後,在收到返回結果之前,不能發起下一次請求),又能傳送非同步請求(是指在單程序單執行緒的程式碼中,發起一次請求後,在等待網站返回結果的時間裡,可以繼續傳送更多請求)。

二、httpx模組基礎使用

2.1 httpx模組安裝

pip install httpx

2.2 httpx模組基礎使用

import httpx
res = httpx.get('http://www.hnxmxit.com/')
print( res.status_code )
print( res.headers )
print( res.content.decode('utf8') )

上述程式碼是通過httpx模組傳送一個開啟網站首頁的情況,然後返回狀態碼、響應頭資訊的例子,讀者應該發現和requests很像。

2.2 模擬請求頭

import httpx

get_param_data = {'wd':'湖南軟測'}
headinfos = {'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/68.0.3440.106 Safari/537.36','Accept-Encoding':'gzip,deflate,br','Accept-Language':'zh-CN,zh;q=0.9','Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9'
       }
response = httpx.get( url='https://www.baidu.com/s',params=get_param_data,headers=headinfos )
print(response.content.decode('utf-8'))

上述程式碼完成在百度中搜索 湖南軟測 的例子,其實寫法完全和requests相同

三、小結:

  • requests 和 httpx都能模擬傳送請求
  • 具一些大神測試後,httpx由於支援非同步請求,所以傳送大量的請求時,httpx的效率是優於requests的

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。