久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁技術文章
文章詳情頁

Python獲取HTTP請求的狀態碼(200,404等)

瀏覽:157日期:2022-06-27 11:59:17

問題描述

Python獲取HTTP請求的狀態碼(200,404等),不訪問整個頁面源碼,那樣太浪費資源:

輸入:segmentfault.com 輸出:200輸入:segmentfault.com/nonexistant 輸出:404

問題解答

回答1:

參考文章:Python實用腳本清單

http不只有get方法(請求頭部+正文),還有head方法,只請求頭部。

import httplibdef get_status_code(host, path='/'): ''' This function retreives the status code of a website by requestingHEAD data from the host. This means that it only requests the headers.If the host cannot be reached or something else goes wrong, it returnsNone instead. ''' try:conn = httplib.HTTPConnection(host)conn.request('HEAD', path)return conn.getresponse().status except StandardError:return Noneprint get_status_code('segmentfault.com') # prints 200print get_status_code('segmentfault.com', '/nonexistant') # prints 404回答2:

你用get請求就會請求整個頭部+正文, 可以試下head方法, 直接訪問頭部!

import requestshtml = requests.head(’http://segmentfault.com’) # 用head方法去請求資源頭部print html.status_code # 狀態碼html = requests.head(’/nonexistant’) # 用head方法去請求資源頭部print html.status_code # 狀態碼# 輸出:200404

標簽: Python 編程
主站蜘蛛池模板: 田林县| 交城县| 揭阳市| 红原县| 万全县| 互助| 安阳市| 肇东市| 镇赉县| 宁南县| 茌平县| 浦东新区| 连城县| 大兴区| 庆云县| 正镶白旗| 马关县| 绥芬河市| 鹤庆县| 信宜市| 张北县| 南陵县| 阳谷县| 江永县| 湟中县| 肇源县| 青州市| 京山县| 汤阴县| 建德市| 琼中| 银川市| 崇州市| 光山县| 余江县| 多伦县| 昭觉县| 句容市| 宜宾县| 玉山县| 岐山县|