日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python构造响应头_Python爬虫库requests获取响应内容、响应状态码、响应头

發布時間:2025/5/22 python 53 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python构造响应头_Python爬虫库requests获取响应内容、响应状态码、响应头 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

首先在程序中引入Requests模塊

import requests

一、獲取不同類型的響應內容

在發送請求后,服務器會返回一個響應內容,而且requests通常會自動解碼響應內容

1.文本響應內容

獲取文本類型的響應內容

r = requests.get('https://www.baidu.com')

r.text # 通過文本的形式獲取響應內容

'\r\n

?\x99??o|??\x80??\x8b??\x8c??\xa0?°±?\x9f¥é\x81\x93 ?\x96°é\x97? hao123 ?\x9c°?\x9b? è§\x86é¢\x91 è′′?\x90§ ?\x99???\x95 ?\x9b′?¤\x9a?o§?\x93\x81

?\x853?o\x8e?\x99??o| About Baidu

?2017?Baidu?????\x94¨?\x99??o|?\x89\x8d??\x85èˉ?? ?\x84\x8fè§\x81?\x8f\x8dé|\x88??o?ICPèˉ\x81030173?\x8f·?

\r\n'

通過encoding來獲取響應內容的編碼以及修改編碼

r.encoding

'ISO-8859-1'

2.二進制響應內容

r.content # 通過content獲取的內容便是二進制類型的

3.JSON響應內容

r.json()

4.原始響應內容

r = requests.get('https://www.baidu.com',stream=True)

print(r.raw) # 就是urllib中的HTTPResponse對象

print(r.raw.read(10))

b'\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03'

二、響應狀態碼

獲取響應狀態碼

r = requests.get('https://www.baidu.com')

r.status_code

200

判斷響應狀態碼

r.status_code == requests.codes.ok

True

當發送一個錯誤請求時,拋出異常

bad_r = requests.get('http://httpbin.org/status/404')

print(bad_r.status_code)

bad_r.raise_for_status()

404

---------------------------------------------------------------------------

HTTPError Traceback (most recent call last)

in ()

1 bad_r = requests.get('http://httpbin.org/status/404')

2 print(bad_r.status_code)

----> 3 bad_r.raise_for_status()

D:\Anaconda3\lib\site-packages\requests\models.py in raise_for_status(self)

926

927 if http_error_msg:

--> 928 raise HTTPError(http_error_msg, response=self)

929

930 def close(self):

HTTPError: 404 Client Error: NOT FOUND for url: http://httpbin.org/status/404

三、響應頭

獲取響應頭

r = requests.get('https://www.baidu.com')

r.headers

{'Cache-Control': 'private, no-cache, no-store, proxy-revalidate, no-transform', 'Connection': 'Keep-Alive', 'Content-Encoding': 'gzip', 'Content-Type': 'text/html', 'Date': 'Mon, 23 Jul 2018 09:04:12 GMT', 'Last-Modified': 'Mon, 23 Jan 2017 13:23:51 GMT', 'Pragma': 'no-cache', 'Server': 'bfe/1.0.8.18', 'Set-Cookie': 'BDORZ=27315; max-age=86400; domain=.baidu.com; path=/', 'Transfer-Encoding': 'chunked'}

獲取響應頭的具體字段

print(r.headers['Server'])

print(r.headers.get('Server'))

bfe/1.0.8.18

bfe/1.0.8.18

更多關于Python爬蟲庫requestsr的使用方法請查看下面的相關鏈接

本文標題: Python爬蟲庫requests獲取響應內容、響應狀態碼、響應頭

本文地址: http://www.cppcns.com/jiaoben/python/299119.html

總結

以上是生活随笔為你收集整理的python构造响应头_Python爬虫库requests获取响应内容、响应状态码、响应头的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。