歡迎您光臨本站 註冊首頁

Python基於httpx模塊實現發送請求

←手機掃碼閱讀     techdo @ 2020-07-08 , reply:0

一、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的              

   


[techdo ] Python基於httpx模塊實現發送請求已經有228次圍觀

http://coctec.com/docs/python/shhow-post-241814.html